darksakura commited on
Commit
f82071f
0 Parent(s):

Duplicate from darksakura/l1

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +36 -0
  2. 12.mp3 +0 -0
  3. Eng_docs.md +109 -0
  4. LICENSE +407 -0
  5. README.md +14 -0
  6. app.cpython-310.pyc +0 -0
  7. cluster/__init__.py +29 -0
  8. cluster/train_cluster.py +89 -0
  9. configs/config-65.json +156 -0
  10. configs/config.json +159 -0
  11. cvec/checkpoint_best_legacy_500.pt +3 -0
  12. data_utils.py +184 -0
  13. diffusion/__init__.py +0 -0
  14. diffusion/__pycache__/__init__.cpython-38.pyc +0 -0
  15. diffusion/__pycache__/data_loaders.cpython-38.pyc +0 -0
  16. diffusion/__pycache__/diffusion.cpython-38.pyc +0 -0
  17. diffusion/__pycache__/dpm_solver_pytorch.cpython-38.pyc +0 -0
  18. diffusion/__pycache__/solver.cpython-38.pyc +0 -0
  19. diffusion/__pycache__/unit2mel.cpython-38.pyc +0 -0
  20. diffusion/__pycache__/vocoder.cpython-38.pyc +0 -0
  21. diffusion/__pycache__/wavenet.cpython-38.pyc +0 -0
  22. diffusion/data_loaders.py +284 -0
  23. diffusion/diffusion.py +317 -0
  24. diffusion/diffusion_onnx.py +612 -0
  25. diffusion/dpm_solver_pytorch.py +1201 -0
  26. diffusion/how to export onnx.md +4 -0
  27. diffusion/infer_gt_mel.py +74 -0
  28. diffusion/logger/__init__.py +0 -0
  29. diffusion/logger/__pycache__/__init__.cpython-38.pyc +0 -0
  30. diffusion/logger/__pycache__/saver.cpython-38.pyc +0 -0
  31. diffusion/logger/__pycache__/utils.cpython-38.pyc +0 -0
  32. diffusion/logger/saver.py +150 -0
  33. diffusion/logger/utils.py +126 -0
  34. diffusion/onnx_export.py +226 -0
  35. diffusion/solver.py +195 -0
  36. diffusion/unit2mel.py +147 -0
  37. diffusion/vocoder.py +94 -0
  38. diffusion/wavenet.py +108 -0
  39. filelists/test.txt +4 -0
  40. filelists/train.txt +15 -0
  41. filelists/val.txt +4 -0
  42. flask_api.py +60 -0
  43. hubert/__init__.py +0 -0
  44. hubert/checkpoint_best_legacy_500.pt +3 -0
  45. hubert/hubert_model.py +222 -0
  46. hubert/hubert_model_onnx.py +217 -0
  47. hubert/put_hubert_ckpt_here +0 -0
  48. inference/__init__.py +0 -0
  49. inference/chunks_temp.json +1 -0
  50. inference/infer_tool.py +533 -0
.gitattributes ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
35
+ Summertime.wav filter=lfs diff=lfs merge=lfs -text
36
+ pretrain/nsf_hifigan/model filter=lfs diff=lfs merge=lfs -text
12.mp3 ADDED
Binary file (206 kB). View file
 
Eng_docs.md ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SoftVC VITS Singing Voice Conversion
2
+
3
+ ## Updates
4
+ > According to incomplete statistics, it seems that training with multiple speakers may lead to **worsened leaking of voice timbre**. It is not recommended to train models with more than 5 speakers. The current suggestion is to try to train models with only a single speaker if you want to achieve a voice timbre that is more similar to the target.
5
+ > Fixed the issue with unwanted staccato, improving audio quality by a decent amount.\
6
+ > The 2.0 version has been moved to the 2.0 branch.\
7
+ > Version 3.0 uses the code structure of FreeVC, which isn't compatible with older versions.\
8
+ > Compared to [DiffSVC](https://github.com/prophesier/diff-svc) , diffsvc performs much better when the training data is of extremely high quality, but this repository may perform better on datasets with lower quality. Additionally, this repository is much faster in terms of inference speed compared to diffsvc.
9
+
10
+ ## Model Overview
11
+ A singing voice coversion (SVC) model, using the SoftVC encoder to extract features from the input audio, sent into VITS along with the F0 to replace the original input to acheive a voice conversion effect. Additionally, changing the vocoder to [NSF HiFiGAN](https://github.com/openvpi/DiffSinger/tree/refactor/modules/nsf_hifigan) to fix the issue with unwanted staccato.
12
+
13
+ ## Notice
14
+ + The current branch is the 32kHz version, which requires less vram during inferencing, as well as faster inferencing speeds, and datasets for said branch take up less disk space. Thus the 32 kHz branch is recommended for use.
15
+ + If you want to train 48 kHz variant models, switch to the [main branch](https://github.com/innnky/so-vits-svc/tree/main).
16
+
17
+
18
+ ## Required models
19
+ + soft vc hubert:[hubert-soft-0d54a1f4.pt](https://github.com/bshall/hubert/releases/download/v0.1/hubert-soft-0d54a1f4.pt)
20
+ + Place under `hubert`.
21
+ + Pretrained models [G_0.pth](https://huggingface.co/innnky/sovits_pretrained/resolve/main/G_0.pth) and [D_0.pth](https://huggingface.co/innnky/sovits_pretrained/resolve/main/D_0.pth)
22
+ + Place under `logs/32k`.
23
+ + Pretrained models are required, because from experiments, training from scratch can be rather unpredictable to say the least, and training with a pretrained model can greatly improve training speeds.
24
+ + The pretrained model includes云灏, 即霜, 辉宇·星AI, 派蒙, and 绫地宁宁, covering the common ranges of both male and female voices, and so it can be seen as a rather universal pretrained model.
25
+ + The pretrained model exludes the `optimizer speaker_embedding` section, rendering it only usable for pretraining and incapable of inferencing with.
26
+ ```shell
27
+ # For simple downloading.
28
+ # hubert
29
+ wget -P hubert/ https://github.com/bshall/hubert/releases/download/v0.1/hubert-soft-0d54a1f4.pt
30
+ # G&D pretrained models
31
+ wget -P logs/32k/ https://huggingface.co/innnky/sovits_pretrained/resolve/main/G_0.pth
32
+ wget -P logs/32k/ https://huggingface.co/innnky/sovits_pretrained/resolve/main/D_0.pth
33
+
34
+ ```
35
+
36
+ ## Colab notebook script for dataset creation and training.
37
+ [colab training notebook](https://colab.research.google.com/drive/1rCUOOVG7-XQlVZuWRAj5IpGrMM8t07pE?usp=sharing)
38
+
39
+ ## Dataset preparation
40
+ All that is required is that the data be put under the `dataset_raw` folder in the structure format provided below.
41
+ ```shell
42
+ dataset_raw
43
+ ├───speaker0
44
+ │ ├───xxx1-xxx1.wav
45
+ │ ├───...
46
+ │ └───Lxx-0xx8.wav
47
+ └───speaker1
48
+ ├───xx2-0xxx2.wav
49
+ ├───...
50
+ └───xxx7-xxx007.wav
51
+ ```
52
+
53
+ ## Data pre-processing.
54
+ 1. Resample to 32khz
55
+
56
+ ```shell
57
+ python resample.py
58
+ ```
59
+ 2. Automatically sort out training set, validation set, test set, and automatically generate configuration files.
60
+ ```shell
61
+ python preprocess_flist_config.py
62
+ # Notice.
63
+ # The n_speakers value in the config will be set automatically according to the amount of speakers in the dataset.
64
+ # To reserve space for additionally added speakers in the dataset, the n_speakers value will be be set to twice the actual amount.
65
+ # If you want even more space for adding more data, you can edit the n_speakers value in the config after runing this step.
66
+ # This can not be changed after training starts.
67
+ ```
68
+ 3. Generate hubert and F0 features/
69
+ ```shell
70
+ python preprocess_hubert_f0.py
71
+ ```
72
+ After running the step above, the `dataset` folder will contain all the pre-processed data, you can delete the `dataset_raw` folder after that.
73
+
74
+ ## Training.
75
+ ```shell
76
+ python train.py -c configs/config.json -m 32k
77
+ ```
78
+
79
+ ## Inferencing.
80
+
81
+ Use [inference_main.py](inference_main.py)
82
+ + Edit `model_path` to your newest checkpoint.
83
+ + Place the input audio under the `raw` folder.
84
+ + Change `clean_names` to the output file name.
85
+ + Use `trans` to edit the pitch shifting amount (semitones).
86
+ + Change `spk_list` to the speaker name.
87
+
88
+ ## Onnx Exporting.
89
+ ### **When exporting Onnx, please make sure you re-clone the whole repository!!!**
90
+ Use [onnx_export.py](onnx_export.py)
91
+ + Create a new folder called `checkpoints`.
92
+ + Create a project folder in `checkpoints` folder with the desired name for your project, let's use `myproject` as example. Folder structure looks like `./checkpoints/myproject`.
93
+ + Rename your model to `model.pth`, rename your config file to `config.json` then move them into `myproject` folder.
94
+ + Modify [onnx_export.py](onnx_export.py) where `path = "NyaruTaffy"`, change `NyaruTaffy` to your project name, here it will be `path = "myproject"`.
95
+ + Run [onnx_export.py](onnx_export.py)
96
+ + Once it finished, a `model.onnx` will be generated in `myproject` folder, that's the model you just exported.
97
+ + Notice: if you want to export a 48K model, please follow the instruction below or use `model_onnx_48k.py` directly.
98
+ + Open [model_onnx.py](model_onnx.py) and change `hps={"sampling_rate": 32000...}` to `hps={"sampling_rate": 48000}` in class `SynthesizerTrn`.
99
+ + Open [nvSTFT](/vdecoder/hifigan/nvSTFT.py) and replace all `32000` with `48000`
100
+ ### Onnx Model UI Support
101
+ + [MoeSS](https://github.com/NaruseMioShirakana/MoeSS)
102
+ + All training function and transformation are removed, only if they are all removed you are actually using Onnx.
103
+
104
+ ## Gradio (WebUI)
105
+ Use [sovits_gradio.py](sovits_gradio.py) to run Gradio WebUI
106
+ + Create a new folder called `checkpoints`.
107
+ + Create a project folder in `checkpoints` folder with the desired name for your project, let's use `myproject` as example. Folder structure looks like `./checkpoints/myproject`.
108
+ + Rename your model to `model.pth`, rename your config file to `config.json` then move them into `myproject` folder.
109
+ + Run [sovits_gradio.py](sovits_gradio.py)
LICENSE ADDED
@@ -0,0 +1,407 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Attribution-NonCommercial 4.0 International
2
+
3
+ =======================================================================
4
+
5
+ Creative Commons Corporation ("Creative Commons") is not a law firm and
6
+ does not provide legal services or legal advice. Distribution of
7
+ Creative Commons public licenses does not create a lawyer-client or
8
+ other relationship. Creative Commons makes its licenses and related
9
+ information available on an "as-is" basis. Creative Commons gives no
10
+ warranties regarding its licenses, any material licensed under their
11
+ terms and conditions, or any related information. Creative Commons
12
+ disclaims all liability for damages resulting from their use to the
13
+ fullest extent possible.
14
+
15
+ Using Creative Commons Public Licenses
16
+
17
+ Creative Commons public licenses provide a standard set of terms and
18
+ conditions that creators and other rights holders may use to share
19
+ original works of authorship and other material subject to copyright
20
+ and certain other rights specified in the public license below. The
21
+ following considerations are for informational purposes only, are not
22
+ exhaustive, and do not form part of our licenses.
23
+
24
+ Considerations for licensors: Our public licenses are
25
+ intended for use by those authorized to give the public
26
+ permission to use material in ways otherwise restricted by
27
+ copyright and certain other rights. Our licenses are
28
+ irrevocable. Licensors should read and understand the terms
29
+ and conditions of the license they choose before applying it.
30
+ Licensors should also secure all rights necessary before
31
+ applying our licenses so that the public can reuse the
32
+ material as expected. Licensors should clearly mark any
33
+ material not subject to the license. This includes other CC-
34
+ licensed material, or material used under an exception or
35
+ limitation to copyright. More considerations for licensors:
36
+ wiki.creativecommons.org/Considerations_for_licensors
37
+
38
+ Considerations for the public: By using one of our public
39
+ licenses, a licensor grants the public permission to use the
40
+ licensed material under specified terms and conditions. If
41
+ the licensor's permission is not necessary for any reason--for
42
+ example, because of any applicable exception or limitation to
43
+ copyright--then that use is not regulated by the license. Our
44
+ licenses grant only permissions under copyright and certain
45
+ other rights that a licensor has authority to grant. Use of
46
+ the licensed material may still be restricted for other
47
+ reasons, including because others have copyright or other
48
+ rights in the material. A licensor may make special requests,
49
+ such as asking that all changes be marked or described.
50
+ Although not required by our licenses, you are encouraged to
51
+ respect those requests where reasonable. More considerations
52
+ for the public:
53
+ wiki.creativecommons.org/Considerations_for_licensees
54
+
55
+ =======================================================================
56
+
57
+ Creative Commons Attribution-NonCommercial 4.0 International Public
58
+ License
59
+
60
+ By exercising the Licensed Rights (defined below), You accept and agree
61
+ to be bound by the terms and conditions of this Creative Commons
62
+ Attribution-NonCommercial 4.0 International Public License ("Public
63
+ License"). To the extent this Public License may be interpreted as a
64
+ contract, You are granted the Licensed Rights in consideration of Your
65
+ acceptance of these terms and conditions, and the Licensor grants You
66
+ such rights in consideration of benefits the Licensor receives from
67
+ making the Licensed Material available under these terms and
68
+ conditions.
69
+
70
+
71
+ Section 1 -- Definitions.
72
+
73
+ a. Adapted Material means material subject to Copyright and Similar
74
+ Rights that is derived from or based upon the Licensed Material
75
+ and in which the Licensed Material is translated, altered,
76
+ arranged, transformed, or otherwise modified in a manner requiring
77
+ permission under the Copyright and Similar Rights held by the
78
+ Licensor. For purposes of this Public License, where the Licensed
79
+ Material is a musical work, performance, or sound recording,
80
+ Adapted Material is always produced where the Licensed Material is
81
+ synched in timed relation with a moving image.
82
+
83
+ b. Adapter's License means the license You apply to Your Copyright
84
+ and Similar Rights in Your contributions to Adapted Material in
85
+ accordance with the terms and conditions of this Public License.
86
+
87
+ c. Copyright and Similar Rights means copyright and/or similar rights
88
+ closely related to copyright including, without limitation,
89
+ performance, broadcast, sound recording, and Sui Generis Database
90
+ Rights, without regard to how the rights are labeled or
91
+ categorized. For purposes of this Public License, the rights
92
+ specified in Section 2(b)(1)-(2) are not Copyright and Similar
93
+ Rights.
94
+ d. Effective Technological Measures means those measures that, in the
95
+ absence of proper authority, may not be circumvented under laws
96
+ fulfilling obligations under Article 11 of the WIPO Copyright
97
+ Treaty adopted on December 20, 1996, and/or similar international
98
+ agreements.
99
+
100
+ e. Exceptions and Limitations means fair use, fair dealing, and/or
101
+ any other exception or limitation to Copyright and Similar Rights
102
+ that applies to Your use of the Licensed Material.
103
+
104
+ f. Licensed Material means the artistic or literary work, database,
105
+ or other material to which the Licensor applied this Public
106
+ License.
107
+
108
+ g. Licensed Rights means the rights granted to You subject to the
109
+ terms and conditions of this Public License, which are limited to
110
+ all Copyright and Similar Rights that apply to Your use of the
111
+ Licensed Material and that the Licensor has authority to license.
112
+
113
+ h. Licensor means the individual(s) or entity(ies) granting rights
114
+ under this Public License.
115
+
116
+ i. NonCommercial means not primarily intended for or directed towards
117
+ commercial advantage or monetary compensation. For purposes of
118
+ this Public License, the exchange of the Licensed Material for
119
+ other material subject to Copyright and Similar Rights by digital
120
+ file-sharing or similar means is NonCommercial provided there is
121
+ no payment of monetary compensation in connection with the
122
+ exchange.
123
+
124
+ j. Share means to provide material to the public by any means or
125
+ process that requires permission under the Licensed Rights, such
126
+ as reproduction, public display, public performance, distribution,
127
+ dissemination, communication, or importation, and to make material
128
+ available to the public including in ways that members of the
129
+ public may access the material from a place and at a time
130
+ individually chosen by them.
131
+
132
+ k. Sui Generis Database Rights means rights other than copyright
133
+ resulting from Directive 96/9/EC of the European Parliament and of
134
+ the Council of 11 March 1996 on the legal protection of databases,
135
+ as amended and/or succeeded, as well as other essentially
136
+ equivalent rights anywhere in the world.
137
+
138
+ l. You means the individual or entity exercising the Licensed Rights
139
+ under this Public License. Your has a corresponding meaning.
140
+
141
+
142
+ Section 2 -- Scope.
143
+
144
+ a. License grant.
145
+
146
+ 1. Subject to the terms and conditions of this Public License,
147
+ the Licensor hereby grants You a worldwide, royalty-free,
148
+ non-sublicensable, non-exclusive, irrevocable license to
149
+ exercise the Licensed Rights in the Licensed Material to:
150
+
151
+ a. reproduce and Share the Licensed Material, in whole or
152
+ in part, for NonCommercial purposes only; and
153
+
154
+ b. produce, reproduce, and Share Adapted Material for
155
+ NonCommercial purposes only.
156
+
157
+ 2. Exceptions and Limitations. For the avoidance of doubt, where
158
+ Exceptions and Limitations apply to Your use, this Public
159
+ License does not apply, and You do not need to comply with
160
+ its terms and conditions.
161
+
162
+ 3. Term. The term of this Public License is specified in Section
163
+ 6(a).
164
+
165
+ 4. Media and formats; technical modifications allowed. The
166
+ Licensor authorizes You to exercise the Licensed Rights in
167
+ all media and formats whether now known or hereafter created,
168
+ and to make technical modifications necessary to do so. The
169
+ Licensor waives and/or agrees not to assert any right or
170
+ authority to forbid You from making technical modifications
171
+ necessary to exercise the Licensed Rights, including
172
+ technical modifications necessary to circumvent Effective
173
+ Technological Measures. For purposes of this Public License,
174
+ simply making modifications authorized by this Section 2(a)
175
+ (4) never produces Adapted Material.
176
+
177
+ 5. Downstream recipients.
178
+
179
+ a. Offer from the Licensor -- Licensed Material. Every
180
+ recipient of the Licensed Material automatically
181
+ receives an offer from the Licensor to exercise the
182
+ Licensed Rights under the terms and conditions of this
183
+ Public License.
184
+
185
+ b. No downstream restrictions. You may not offer or impose
186
+ any additional or different terms or conditions on, or
187
+ apply any Effective Technological Measures to, the
188
+ Licensed Material if doing so restricts exercise of the
189
+ Licensed Rights by any recipient of the Licensed
190
+ Material.
191
+
192
+ 6. No endorsement. Nothing in this Public License constitutes or
193
+ may be construed as permission to assert or imply that You
194
+ are, or that Your use of the Licensed Material is, connected
195
+ with, or sponsored, endorsed, or granted official status by,
196
+ the Licensor or others designated to receive attribution as
197
+ provided in Section 3(a)(1)(A)(i).
198
+
199
+ b. Other rights.
200
+
201
+ 1. Moral rights, such as the right of integrity, are not
202
+ licensed under this Public License, nor are publicity,
203
+ privacy, and/or other similar personality rights; however, to
204
+ the extent possible, the Licensor waives and/or agrees not to
205
+ assert any such rights held by the Licensor to the limited
206
+ extent necessary to allow You to exercise the Licensed
207
+ Rights, but not otherwise.
208
+
209
+ 2. Patent and trademark rights are not licensed under this
210
+ Public License.
211
+
212
+ 3. To the extent possible, the Licensor waives any right to
213
+ collect royalties from You for the exercise of the Licensed
214
+ Rights, whether directly or through a collecting society
215
+ under any voluntary or waivable statutory or compulsory
216
+ licensing scheme. In all other cases the Licensor expressly
217
+ reserves any right to collect such royalties, including when
218
+ the Licensed Material is used other than for NonCommercial
219
+ purposes.
220
+
221
+
222
+ Section 3 -- License Conditions.
223
+
224
+ Your exercise of the Licensed Rights is expressly made subject to the
225
+ following conditions.
226
+
227
+ a. Attribution.
228
+
229
+ 1. If You Share the Licensed Material (including in modified
230
+ form), You must:
231
+
232
+ a. retain the following if it is supplied by the Licensor
233
+ with the Licensed Material:
234
+
235
+ i. identification of the creator(s) of the Licensed
236
+ Material and any others designated to receive
237
+ attribution, in any reasonable manner requested by
238
+ the Licensor (including by pseudonym if
239
+ designated);
240
+
241
+ ii. a copyright notice;
242
+
243
+ iii. a notice that refers to this Public License;
244
+
245
+ iv. a notice that refers to the disclaimer of
246
+ warranties;
247
+
248
+ v. a URI or hyperlink to the Licensed Material to the
249
+ extent reasonably practicable;
250
+
251
+ b. indicate if You modified the Licensed Material and
252
+ retain an indication of any previous modifications; and
253
+
254
+ c. indicate the Licensed Material is licensed under this
255
+ Public License, and include the text of, or the URI or
256
+ hyperlink to, this Public License.
257
+
258
+ 2. You may satisfy the conditions in Section 3(a)(1) in any
259
+ reasonable manner based on the medium, means, and context in
260
+ which You Share the Licensed Material. For example, it may be
261
+ reasonable to satisfy the conditions by providing a URI or
262
+ hyperlink to a resource that includes the required
263
+ information.
264
+
265
+ 3. If requested by the Licensor, You must remove any of the
266
+ information required by Section 3(a)(1)(A) to the extent
267
+ reasonably practicable.
268
+
269
+ 4. If You Share Adapted Material You produce, the Adapter's
270
+ License You apply must not prevent recipients of the Adapted
271
+ Material from complying with this Public License.
272
+
273
+
274
+ Section 4 -- Sui Generis Database Rights.
275
+
276
+ Where the Licensed Rights include Sui Generis Database Rights that
277
+ apply to Your use of the Licensed Material:
278
+
279
+ a. for the avoidance of doubt, Section 2(a)(1) grants You the right
280
+ to extract, reuse, reproduce, and Share all or a substantial
281
+ portion of the contents of the database for NonCommercial purposes
282
+ only;
283
+
284
+ b. if You include all or a substantial portion of the database
285
+ contents in a database in which You have Sui Generis Database
286
+ Rights, then the database in which You have Sui Generis Database
287
+ Rights (but not its individual contents) is Adapted Material; and
288
+
289
+ c. You must comply with the conditions in Section 3(a) if You Share
290
+ all or a substantial portion of the contents of the database.
291
+
292
+ For the avoidance of doubt, this Section 4 supplements and does not
293
+ replace Your obligations under this Public License where the Licensed
294
+ Rights include other Copyright and Similar Rights.
295
+
296
+
297
+ Section 5 -- Disclaimer of Warranties and Limitation of Liability.
298
+
299
+ a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
300
+ EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
301
+ AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
302
+ ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
303
+ IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
304
+ WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
305
+ PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
306
+ ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
307
+ KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
308
+ ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
309
+
310
+ b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
311
+ TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
312
+ NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
313
+ INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
314
+ COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
315
+ USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
316
+ ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
317
+ DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
318
+ IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
319
+
320
+ c. The disclaimer of warranties and limitation of liability provided
321
+ above shall be interpreted in a manner that, to the extent
322
+ possible, most closely approximates an absolute disclaimer and
323
+ waiver of all liability.
324
+
325
+
326
+ Section 6 -- Term and Termination.
327
+
328
+ a. This Public License applies for the term of the Copyright and
329
+ Similar Rights licensed here. However, if You fail to comply with
330
+ this Public License, then Your rights under this Public License
331
+ terminate automatically.
332
+
333
+ b. Where Your right to use the Licensed Material has terminated under
334
+ Section 6(a), it reinstates:
335
+
336
+ 1. automatically as of the date the violation is cured, provided
337
+ it is cured within 30 days of Your discovery of the
338
+ violation; or
339
+
340
+ 2. upon express reinstatement by the Licensor.
341
+
342
+ For the avoidance of doubt, this Section 6(b) does not affect any
343
+ right the Licensor may have to seek remedies for Your violations
344
+ of this Public License.
345
+
346
+ c. For the avoidance of doubt, the Licensor may also offer the
347
+ Licensed Material under separate terms or conditions or stop
348
+ distributing the Licensed Material at any time; however, doing so
349
+ will not terminate this Public License.
350
+
351
+ d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
352
+ License.
353
+
354
+
355
+ Section 7 -- Other Terms and Conditions.
356
+
357
+ a. The Licensor shall not be bound by any additional or different
358
+ terms or conditions communicated by You unless expressly agreed.
359
+
360
+ b. Any arrangements, understandings, or agreements regarding the
361
+ Licensed Material not stated herein are separate from and
362
+ independent of the terms and conditions of this Public License.
363
+
364
+
365
+ Section 8 -- Interpretation.
366
+
367
+ a. For the avoidance of doubt, this Public License does not, and
368
+ shall not be interpreted to, reduce, limit, restrict, or impose
369
+ conditions on any use of the Licensed Material that could lawfully
370
+ be made without permission under this Public License.
371
+
372
+ b. To the extent possible, if any provision of this Public License is
373
+ deemed unenforceable, it shall be automatically reformed to the
374
+ minimum extent necessary to make it enforceable. If the provision
375
+ cannot be reformed, it shall be severed from this Public License
376
+ without affecting the enforceability of the remaining terms and
377
+ conditions.
378
+
379
+ c. No term or condition of this Public License will be waived and no
380
+ failure to comply consented to unless expressly agreed to by the
381
+ Licensor.
382
+
383
+ d. Nothing in this Public License constitutes or may be interpreted
384
+ as a limitation upon, or waiver of, any privileges and immunities
385
+ that apply to the Licensor or You, including from the legal
386
+ processes of any jurisdiction or authority.
387
+
388
+ =======================================================================
389
+
390
+ Creative Commons is not a party to its public
391
+ licenses. Notwithstanding, Creative Commons may elect to apply one of
392
+ its public licenses to material it publishes and in those instances
393
+ will be considered the “Licensor.” The text of the Creative Commons
394
+ public licenses is dedicated to the public domain under the CC0 Public
395
+ Domain Dedication. Except for the limited purpose of indicating that
396
+ material is shared under a Creative Commons public license or as
397
+ otherwise permitted by the Creative Commons policies published at
398
+ creativecommons.org/policies, Creative Commons does not authorize the
399
+ use of the trademark "Creative Commons" or any other trademark or logo
400
+ of Creative Commons without its prior written consent including,
401
+ without limitation, in connection with any unauthorized modifications
402
+ to any of its public licenses or any other arrangements,
403
+ understandings, or agreements concerning use of licensed material. For
404
+ the avoidance of doubt, this paragraph does not form part of the
405
+ public licenses.
406
+
407
+ Creative Commons may be contacted at creativecommons.org.
README.md ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: 🏆
3
+ emoji: 🏆
4
+ colorFrom: gray
5
+ colorTo: pink
6
+ sdk: gradio
7
+ sdk_version: 3.18.0
8
+ app_file: app.cpython-310.pyc
9
+ pinned: false
10
+ license: mit
11
+ duplicated_from: darksakura/l1
12
+ ---
13
+
14
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.cpython-310.pyc ADDED
Binary file (12.4 kB). View file
 
cluster/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ from sklearn.cluster import KMeans
4
+
5
+ def get_cluster_model(ckpt_path):
6
+ checkpoint = torch.load(ckpt_path)
7
+ kmeans_dict = {}
8
+ for spk, ckpt in checkpoint.items():
9
+ km = KMeans(ckpt["n_features_in_"])
10
+ km.__dict__["n_features_in_"] = ckpt["n_features_in_"]
11
+ km.__dict__["_n_threads"] = ckpt["_n_threads"]
12
+ km.__dict__["cluster_centers_"] = ckpt["cluster_centers_"]
13
+ kmeans_dict[spk] = km
14
+ return kmeans_dict
15
+
16
+ def get_cluster_result(model, x, speaker):
17
+ """
18
+ x: np.array [t, 256]
19
+ return cluster class result
20
+ """
21
+ return model[speaker].predict(x)
22
+
23
+ def get_cluster_center_result(model, x,speaker):
24
+ """x: np.array [t, 256]"""
25
+ predict = model[speaker].predict(x)
26
+ return model[speaker].cluster_centers_[predict]
27
+
28
+ def get_center(model, x,speaker):
29
+ return model[speaker].cluster_centers_[x]
cluster/train_cluster.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from glob import glob
3
+ from pathlib import Path
4
+ import torch
5
+ import logging
6
+ import argparse
7
+ import torch
8
+ import numpy as np
9
+ from sklearn.cluster import KMeans, MiniBatchKMeans
10
+ import tqdm
11
+ logging.basicConfig(level=logging.INFO)
12
+ logger = logging.getLogger(__name__)
13
+ import time
14
+ import random
15
+
16
+ def train_cluster(in_dir, n_clusters, use_minibatch=True, verbose=False):
17
+
18
+ logger.info(f"Loading features from {in_dir}")
19
+ features = []
20
+ nums = 0
21
+ for path in tqdm.tqdm(in_dir.glob("*.soft.pt")):
22
+ features.append(torch.load(path).squeeze(0).numpy().T)
23
+ # print(features[-1].shape)
24
+ features = np.concatenate(features, axis=0)
25
+ print(nums, features.nbytes/ 1024**2, "MB , shape:",features.shape, features.dtype)
26
+ features = features.astype(np.float32)
27
+ logger.info(f"Clustering features of shape: {features.shape}")
28
+ t = time.time()
29
+ if use_minibatch:
30
+ kmeans = MiniBatchKMeans(n_clusters=n_clusters,verbose=verbose, batch_size=4096, max_iter=80).fit(features)
31
+ else:
32
+ kmeans = KMeans(n_clusters=n_clusters,verbose=verbose).fit(features)
33
+ print(time.time()-t, "s")
34
+
35
+ x = {
36
+ "n_features_in_": kmeans.n_features_in_,
37
+ "_n_threads": kmeans._n_threads,
38
+ "cluster_centers_": kmeans.cluster_centers_,
39
+ }
40
+ print("end")
41
+
42
+ return x
43
+
44
+
45
+ if __name__ == "__main__":
46
+
47
+ parser = argparse.ArgumentParser()
48
+ parser.add_argument('--dataset', type=Path, default="./dataset/44k",
49
+ help='path of training data directory')
50
+ parser.add_argument('--output', type=Path, default="logs/44k",
51
+ help='path of model output directory')
52
+
53
+ args = parser.parse_args()
54
+
55
+ checkpoint_dir = args.output
56
+ dataset = args.dataset
57
+ n_clusters = 10000
58
+
59
+ ckpt = {}
60
+ for spk in os.listdir(dataset):
61
+ if os.path.isdir(dataset/spk):
62
+ print(f"train kmeans for {spk}...")
63
+ in_dir = dataset/spk
64
+ x = train_cluster(in_dir, n_clusters, verbose=False)
65
+ ckpt[spk] = x
66
+
67
+ checkpoint_path = checkpoint_dir / f"kmeans_{n_clusters}.pt"
68
+ checkpoint_path.parent.mkdir(exist_ok=True, parents=True)
69
+ torch.save(
70
+ ckpt,
71
+ checkpoint_path,
72
+ )
73
+
74
+
75
+ # import cluster
76
+ # for spk in tqdm.tqdm(os.listdir("dataset")):
77
+ # if os.path.isdir(f"dataset/{spk}"):
78
+ # print(f"start kmeans inference for {spk}...")
79
+ # for feature_path in tqdm.tqdm(glob(f"dataset/{spk}/*.discrete.npy", recursive=True)):
80
+ # mel_path = feature_path.replace(".discrete.npy",".mel.npy")
81
+ # mel_spectrogram = np.load(mel_path)
82
+ # feature_len = mel_spectrogram.shape[-1]
83
+ # c = np.load(feature_path)
84
+ # c = utils.tools.repeat_expand_2d(torch.FloatTensor(c), feature_len).numpy()
85
+ # feature = c.T
86
+ # feature_class = cluster.get_cluster_result(feature, spk)
87
+ # np.save(feature_path.replace(".discrete.npy", ".discrete_class.npy"), feature_class)
88
+
89
+
configs/config-65.json ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "train": {
3
+ "log_interval": 200,
4
+ "eval_interval": 1600,
5
+ "seed": 1234,
6
+ "epochs": 10000,
7
+ "learning_rate": 0.0001,
8
+ "betas": [
9
+ 0.8,
10
+ 0.99
11
+ ],
12
+ "eps": 1e-09,
13
+ "batch_size": 1,
14
+ "fp16_run": false,
15
+ "lr_decay": 0.999875,
16
+ "segment_size": 10240,
17
+ "init_lr_ratio": 1,
18
+ "warmup_epochs": 0,
19
+ "c_mel": 45,
20
+ "c_kl": 1.0,
21
+ "use_sr": true,
22
+ "max_speclen": 512,
23
+ "port": "8001",
24
+ "keep_ckpts": 53,
25
+ "all_in_mem": false
26
+ },
27
+ "data": {
28
+ "training_files": "filelists/train.txt",
29
+ "validation_files": "filelists/val.txt",
30
+ "max_wav_value": 32768.0,
31
+ "sampling_rate": 44100,
32
+ "filter_length": 2048,
33
+ "hop_length": 512,
34
+ "win_length": 2048,
35
+ "n_mel_channels": 80,
36
+ "mel_fmin": 0.0,
37
+ "mel_fmax": 22050
38
+ },
39
+ "model": {
40
+ "inter_channels": 192,
41
+ "hidden_channels": 192,
42
+ "filter_channels": 768,
43
+ "n_heads": 2,
44
+ "n_layers": 6,
45
+ "kernel_size": 3,
46
+ "p_dropout": 0.1,
47
+ "resblock": "1",
48
+ "resblock_kernel_sizes": [
49
+ 3,
50
+ 7,
51
+ 11
52
+ ],
53
+ "resblock_dilation_sizes": [
54
+ [
55
+ 1,
56
+ 3,
57
+ 5
58
+ ],
59
+ [
60
+ 1,
61
+ 3,
62
+ 5
63
+ ],
64
+ [
65
+ 1,
66
+ 3,
67
+ 5
68
+ ]
69
+ ],
70
+ "upsample_rates": [
71
+ 8,
72
+ 8,
73
+ 2,
74
+ 2,
75
+ 2
76
+ ],
77
+ "upsample_initial_channel": 512,
78
+ "upsample_kernel_sizes": [
79
+ 16,
80
+ 16,
81
+ 4,
82
+ 4,
83
+ 4
84
+ ],
85
+ "n_layers_q": 3,
86
+ "use_spectral_norm": false,
87
+ "gin_channels": 256,
88
+ "ssl_dim": 256,
89
+ "n_speakers": 63
90
+ },
91
+ "spk": {
92
+ "AKIMOTO_MANATSU": 0,
93
+ "ENDO_SAKURA": 1,
94
+ "ETO_MISA": 2,
95
+ "HARUKA_KUROMI": 3,
96
+ "HAYAKAWA_SEIRA": 4,
97
+ "HIGUCHI_HINA": 5,
98
+ "HORI_MIONA": 6,
99
+ "HOSHINO_MINAMI": 7,
100
+ "ICHINOSE_MIKU": 8,
101
+ "IKEDA_TERESA": 9,
102
+ "IKUTA_ERIKA": 10,
103
+ "INOUE_NAGI": 11,
104
+ "INOUE_SAYURI": 12,
105
+ "IOKI_MAO": 13,
106
+ "ITO_JUNNA": 14,
107
+ "ITO_RIRIA": 15,
108
+ "IWAMOTO_RENKA": 16,
109
+ "KAKEHASHI_SAYAKA": 17,
110
+ "KAKI_HARUKA": 18,
111
+ "KANAGAWA_SAYA": 19,
112
+ "KAWAGO_HINA": 20,
113
+ "KAWASAKI_SAKURA": 21,
114
+ "KITAGAWA_YURI": 22,
115
+ "KITANO_HINAKO": 23,
116
+ "KUBO_SHIORI": 24,
117
+ "MATSUMURA_SAYURI": 25,
118
+ "MIYU_MATSUO": 26,
119
+ "MUKAI_HAZUKI": 27,
120
+ "NAKAMURA_RENO": 28,
121
+ "NAKANISHI_ARUNO": 29,
122
+ "NAO_YUMIKI": 30,
123
+ "NISHINO_NANASE": 31,
124
+ "NOUJO_AMI": 32,
125
+ "OGAWA_AYA": 33,
126
+ "OKUDA_IROHA": 34,
127
+ "OZONO_MOMOKO": 35,
128
+ "RIKA_SATO": 36,
129
+ "RUNA_HAYASHI": 37,
130
+ "SAGARA_IORI": 38,
131
+ "SAITO_ASUKA": 39,
132
+ "SAKAGUCHI_TAMAMI": 40,
133
+ "SAKURAI_REIKA": 41,
134
+ "SASAKI_KOTOKO": 42,
135
+ "SATO_KAEDE": 43,
136
+ "SATO_YUURI": 44,
137
+ "SHIBATA_YUNA": 45,
138
+ "SHINUCHI_MAI": 46,
139
+ "SHIRAISHI_MAI": 47,
140
+ "SUGAWARA_SATSUKI": 48,
141
+ "SUZUKI_AYANE": 49,
142
+ "TAKAYAMA_KAZUMI": 50,
143
+ "TAMURA_MAYU": 51,
144
+ "TERADA_RANZE": 52,
145
+ "TOMISATO_NAO": 53,
146
+ "TSUTSUI_AYAME": 54,
147
+ "UMEZAWA_MINAMI": 55,
148
+ "WADA_MAAYA": 56,
149
+ "WAKATSUKI_YUMI": 57,
150
+ "WATANABE_MIRIA": 58,
151
+ "YAKUBO_MIO": 59,
152
+ "YAMASHITA_MIZUKI": 60,
153
+ "YAMAZAKI_RENA": 61,
154
+ "YODA_YUUKI": 62
155
+ }
156
+ }
configs/config.json ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "train": {
3
+ "log_interval": 200,
4
+ "eval_interval": 1800,
5
+ "seed": 1234,
6
+ "epochs": 10000,
7
+ "learning_rate": 0.0001,
8
+ "betas": [
9
+ 0.8,
10
+ 0.99
11
+ ],
12
+ "eps": 1e-09,
13
+ "batch_size": 32,
14
+ "fp16_run": false,
15
+ "lr_decay": 0.999875,
16
+ "segment_size": 10240,
17
+ "init_lr_ratio": 1,
18
+ "warmup_epochs": 0,
19
+ "c_mel": 45,
20
+ "c_kl": 1.0,
21
+ "use_sr": true,
22
+ "max_speclen": 512,
23
+ "port": "8001",
24
+ "keep_ckpts": 40,
25
+ "all_in_mem": false,
26
+ "vol_aug": true
27
+ },
28
+ "data": {
29
+ "training_files": "filelists/train.txt",
30
+ "validation_files": "filelists/val.txt",
31
+ "max_wav_value": 32768.0,
32
+ "sampling_rate": 44100,
33
+ "filter_length": 2048,
34
+ "hop_length": 512,
35
+ "win_length": 2048,
36
+ "n_mel_channels": 80,
37
+ "mel_fmin": 0.0,
38
+ "mel_fmax": 22050
39
+ },
40
+ "model": {
41
+ "inter_channels": 192,
42
+ "hidden_channels": 192,
43
+ "filter_channels": 768,
44
+ "n_heads": 2,
45
+ "n_layers": 6,
46
+ "kernel_size": 3,
47
+ "p_dropout": 0.1,
48
+ "resblock": "1",
49
+ "resblock_kernel_sizes": [
50
+ 3,
51
+ 7,
52
+ 11
53
+ ],
54
+ "resblock_dilation_sizes": [
55
+ [
56
+ 1,
57
+ 3,
58
+ 5
59
+ ],
60
+ [
61
+ 1,
62
+ 3,
63
+ 5
64
+ ],
65
+ [
66
+ 1,
67
+ 3,
68
+ 5
69
+ ]
70
+ ],
71
+ "upsample_rates": [
72
+ 8,
73
+ 8,
74
+ 2,
75
+ 2,
76
+ 2
77
+ ],
78
+ "upsample_initial_channel": 512,
79
+ "upsample_kernel_sizes": [
80
+ 16,
81
+ 16,
82
+ 4,
83
+ 4,
84
+ 4
85
+ ],
86
+ "n_layers_q": 3,
87
+ "use_spectral_norm": false,
88
+ "gin_channels": 768,
89
+ "ssl_dim": 768,
90
+ "n_speakers": 62,
91
+ "speech_encoder": "vec768l12",
92
+ "speaker_embedding": false,
93
+ "vol_embedding": true
94
+ },
95
+ "spk": {
96
+ "AKIMOTO_MANATSU": 0,
97
+ "ENDO_SAKURA": 1,
98
+ "ETO_MISA": 2,
99
+ "HARUKA_KUROMI": 3,
100
+ "HASHIMOTO_NANAMI": 4,
101
+ "HAYAKAWA_SEIRA": 5,
102
+ "HIGUCHI_HINA": 6,
103
+ "HORI_MIONA": 7,
104
+ "HOSHINO_MINAMI": 8,
105
+ "ICHINOSE_MIKU": 9,
106
+ "IKEDA_TERESA": 10,
107
+ "IKUTA_ERIKA": 11,
108
+ "INOUE_NAGI": 12,
109
+ "INOUE_SAYURI": 13,
110
+ "IOKI_MAO": 14,
111
+ "ITO_JUNNA": 15,
112
+ "ITO_RIRIA": 16,
113
+ "IWAMOTO_RENKA": 17,
114
+ "KAKEHASHI_SAYAKA": 18,
115
+ "KAKI_HARUKA": 19,
116
+ "KANAGAWA_SAYA": 20,
117
+ "KAWAGO_HINA": 21,
118
+ "KAWASAKI_SAKURA": 22,
119
+ "KITAGAWA_YURI": 23,
120
+ "KITANO_HINAKO": 24,
121
+ "KUBO_SHIORI": 25,
122
+ "MATSUMURA_SAYURI": 26,
123
+ "MIYU_MATSUO": 27,
124
+ "MUKAI_HAZUKI": 28,
125
+ "NAKAMURA_RENO": 29,
126
+ "NAKANISHI_ARUNO": 30,
127
+ "NAO_YUMIKI": 31,
128
+ "NISHINO_NANASE": 32,
129
+ "OGAWA_AYA": 33,
130
+ "OKUDA_IROHA": 34,
131
+ "OZONO_MOMOKO": 35,
132
+ "RIKA_SATO": 36,
133
+ "RUNA_HAYASHI": 37,
134
+ "SAITO_ASUKA": 38,
135
+ "SAKAGUCHI_TAMAMI": 39,
136
+ "SAKURAI_REIKA": 40,
137
+ "SASAKI_KOTOKO": 41,
138
+ "SATO_KAEDE": 42,
139
+ "SATO_YUURI": 43,
140
+ "SEIMIYA_REI": 44,
141
+ "SHIBATA_YUNA": 45,
142
+ "SHINUCHI_MAI": 46,
143
+ "SHIRAISHI_MAI": 47,
144
+ "SUGAWARA_SATSUKI": 48,
145
+ "SUZUKI_AYANE": 49,
146
+ "TAKAYAMA_KAZUMI": 50,
147
+ "TAMURA_MAYU": 51,
148
+ "TERADA_RANZE": 52,
149
+ "TOMISATO_NAO": 53,
150
+ "TSUTSUI_AYAME": 54,
151
+ "UMEZAWA_MINAMI": 55,
152
+ "WAKATSUKI_YUMI": 56,
153
+ "WATANABE_MIRIA": 57,
154
+ "YAKUBO_MIO": 58,
155
+ "YAMASHITA_MIZUKI": 59,
156
+ "YAMAZAKI_RENA": 60,
157
+ "YODA_YUUKI": 61
158
+ }
159
+ }
cvec/checkpoint_best_legacy_500.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:294a2e8c98136070a999e040ec98dfa5a99b88a7938181c56cc2ab0e2f6ce0e8
3
+ size 48501067
data_utils.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ import os
3
+ import random
4
+ import numpy as np
5
+ import torch
6
+ import torch.utils.data
7
+
8
+ import modules.commons as commons
9
+ import utils
10
+ from modules.mel_processing import spectrogram_torch, spec_to_mel_torch, spectrogram_torch
11
+ from utils import load_wav_to_torch, load_filepaths_and_text
12
+
13
+ # import h5py
14
+
15
+
16
+ """Multi speaker version"""
17
+
18
+
19
+ class TextAudioSpeakerLoader(torch.utils.data.Dataset):
20
+ """
21
+ 1) loads audio, speaker_id, text pairs
22
+ 2) normalizes text and converts them to sequences of integers
23
+ 3) computes spectrograms from audio files.
24
+ """
25
+
26
+ def __init__(self, audiopaths, hparams, all_in_mem: bool = False, vol_aug: bool = True):
27
+ self.audiopaths = load_filepaths_and_text(audiopaths)
28
+ self.hparams = hparams
29
+ self.max_wav_value = hparams.data.max_wav_value
30
+ self.sampling_rate = hparams.data.sampling_rate
31
+ self.filter_length = hparams.data.filter_length
32
+ self.hop_length = hparams.data.hop_length
33
+ self.win_length = hparams.data.win_length
34
+ self.sampling_rate = hparams.data.sampling_rate
35
+ self.use_sr = hparams.train.use_sr
36
+ self.spec_len = hparams.train.max_speclen
37
+ self.spk_map = hparams.spk
38
+ self.vol_emb = hparams.model.vol_embedding
39
+ self.vol_aug = hparams.train.vol_aug and vol_aug
40
+ random.seed(1234)
41
+ random.shuffle(self.audiopaths)
42
+
43
+ self.all_in_mem = all_in_mem
44
+ if self.all_in_mem:
45
+ self.cache = [self.get_audio(p[0]) for p in self.audiopaths]
46
+
47
+ def get_audio(self, filename):
48
+ filename = filename.replace("\\", "/")
49
+ audio, sampling_rate = load_wav_to_torch(filename)
50
+ if sampling_rate != self.sampling_rate:
51
+ raise ValueError("{} SR doesn't match target {} SR".format(
52
+ sampling_rate, self.sampling_rate))
53
+ audio_norm = audio / self.max_wav_value
54
+ audio_norm = audio_norm.unsqueeze(0)
55
+ spec_filename = filename.replace(".wav", ".spec.pt")
56
+
57
+ # Ideally, all data generated after Mar 25 should have .spec.pt
58
+ if os.path.exists(spec_filename):
59
+ spec = torch.load(spec_filename)
60
+ else:
61
+ spec = spectrogram_torch(audio_norm, self.filter_length,
62
+ self.sampling_rate, self.hop_length, self.win_length,
63
+ center=False)
64
+ spec = torch.squeeze(spec, 0)
65
+ torch.save(spec, spec_filename)
66
+
67
+ spk = filename.split("/")[-2]
68
+ spk = torch.LongTensor([self.spk_map[spk]])
69
+
70
+ f0, uv = np.load(filename + ".f0.npy",allow_pickle=True)
71
+
72
+ f0 = torch.FloatTensor(np.array(f0,dtype=float))
73
+ uv = torch.FloatTensor(np.array(uv,dtype=float))
74
+
75
+ c = torch.load(filename+ ".soft.pt")
76
+ c = utils.repeat_expand_2d(c.squeeze(0), f0.shape[0])
77
+ if self.vol_emb:
78
+ volume_path = filename + ".vol.npy"
79
+ volume = np.load(volume_path)
80
+ volume = torch.from_numpy(volume).float()
81
+ else:
82
+ volume = None
83
+
84
+ lmin = min(c.size(-1), spec.size(-1))
85
+ assert abs(c.size(-1) - spec.size(-1)) < 3, (c.size(-1), spec.size(-1), f0.shape, filename)
86
+ assert abs(audio_norm.shape[1]-lmin * self.hop_length) < 3 * self.hop_length
87
+ spec, c, f0, uv = spec[:, :lmin], c[:, :lmin], f0[:lmin], uv[:lmin]
88
+ audio_norm = audio_norm[:, :lmin * self.hop_length]
89
+ if volume!= None:
90
+ volume = volume[:lmin]
91
+ return c, f0, spec, audio_norm, spk, uv, volume
92
+
93
+ def random_slice(self, c, f0, spec, audio_norm, spk, uv, volume):
94
+ # if spec.shape[1] < 30:
95
+ # print("skip too short audio:", filename)
96
+ # return None
97
+
98
+ if random.choice([True, False]) and self.vol_aug and volume!=None:
99
+ max_amp = float(torch.max(torch.abs(audio_norm))) + 1e-5
100
+ max_shift = min(1, np.log10(1/max_amp))
101
+ log10_vol_shift = random.uniform(-1, max_shift)
102
+ audio_norm = audio_norm * (10 ** log10_vol_shift)
103
+ volume = volume * (10 ** log10_vol_shift)
104
+ spec = spectrogram_torch(audio_norm,
105
+ self.hparams.data.filter_length,
106
+ self.hparams.data.sampling_rate,
107
+ self.hparams.data.hop_length,
108
+ self.hparams.data.win_length,
109
+ center=False)[0]
110
+
111
+ if spec.shape[1] > 800:
112
+ start = random.randint(0, spec.shape[1]-800)
113
+ end = start + 790
114
+ spec, c, f0, uv = spec[:, start:end], c[:, start:end], f0[start:end], uv[start:end]
115
+ audio_norm = audio_norm[:, start * self.hop_length : end * self.hop_length]
116
+ if volume !=None:
117
+ volume = volume[start:end]
118
+ return c, f0, spec, audio_norm, spk, uv,volume
119
+
120
+ def __getitem__(self, index):
121
+ if self.all_in_mem:
122
+ return self.random_slice(*self.cache[index])
123
+ else:
124
+ return self.random_slice(*self.get_audio(self.audiopaths[index][0]))
125
+
126
+ def __len__(self):
127
+ return len(self.audiopaths)
128
+
129
+
130
+ class TextAudioCollate:
131
+
132
+ def __call__(self, batch):
133
+ batch = [b for b in batch if b is not None]
134
+
135
+ input_lengths, ids_sorted_decreasing = torch.sort(
136
+ torch.LongTensor([x[0].shape[1] for x in batch]),
137
+ dim=0, descending=True)
138
+
139
+ max_c_len = max([x[0].size(1) for x in batch])
140
+ max_wav_len = max([x[3].size(1) for x in batch])
141
+
142
+ lengths = torch.LongTensor(len(batch))
143
+
144
+ c_padded = torch.FloatTensor(len(batch), batch[0][0].shape[0], max_c_len)
145
+ f0_padded = torch.FloatTensor(len(batch), max_c_len)
146
+ spec_padded = torch.FloatTensor(len(batch), batch[0][2].shape[0], max_c_len)
147
+ wav_padded = torch.FloatTensor(len(batch), 1, max_wav_len)
148
+ spkids = torch.LongTensor(len(batch), 1)
149
+ uv_padded = torch.FloatTensor(len(batch), max_c_len)
150
+ volume_padded = torch.FloatTensor(len(batch), max_c_len)
151
+
152
+ c_padded.zero_()
153
+ spec_padded.zero_()
154
+ f0_padded.zero_()
155
+ wav_padded.zero_()
156
+ uv_padded.zero_()
157
+ volume_padded.zero_()
158
+
159
+ for i in range(len(ids_sorted_decreasing)):
160
+ row = batch[ids_sorted_decreasing[i]]
161
+
162
+ c = row[0]
163
+ c_padded[i, :, :c.size(1)] = c
164
+ lengths[i] = c.size(1)
165
+
166
+ f0 = row[1]
167
+ f0_padded[i, :f0.size(0)] = f0
168
+
169
+ spec = row[2]
170
+ spec_padded[i, :, :spec.size(1)] = spec
171
+
172
+ wav = row[3]
173
+ wav_padded[i, :, :wav.size(1)] = wav
174
+
175
+ spkids[i, 0] = row[4]
176
+
177
+ uv = row[5]
178
+ uv_padded[i, :uv.size(0)] = uv
179
+ volume = row[6]
180
+ if volume != None:
181
+ volume_padded[i, :volume.size(0)] = volume
182
+ else :
183
+ volume_padded = None
184
+ return c_padded, f0_padded, spec_padded, wav_padded, spkids, lengths, uv_padded, volume_padded
diffusion/__init__.py ADDED
File without changes
diffusion/__pycache__/__init__.cpython-38.pyc ADDED
Binary file (131 Bytes). View file
 
diffusion/__pycache__/data_loaders.cpython-38.pyc ADDED
Binary file (5.7 kB). View file
 
diffusion/__pycache__/diffusion.cpython-38.pyc ADDED
Binary file (10.1 kB). View file
 
diffusion/__pycache__/dpm_solver_pytorch.cpython-38.pyc ADDED
Binary file (50.4 kB). View file
 
diffusion/__pycache__/solver.cpython-38.pyc ADDED
Binary file (4.04 kB). View file
 
diffusion/__pycache__/unit2mel.cpython-38.pyc ADDED
Binary file (4.43 kB). View file
 
diffusion/__pycache__/vocoder.cpython-38.pyc ADDED
Binary file (3.5 kB). View file
 
diffusion/__pycache__/wavenet.cpython-38.pyc ADDED
Binary file (3.84 kB). View file
 
diffusion/data_loaders.py ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import random
3
+ import re
4
+ import numpy as np
5
+ import librosa
6
+ import torch
7
+ import random
8
+ from utils import repeat_expand_2d
9
+ from tqdm import tqdm
10
+ from torch.utils.data import Dataset
11
+
12
+ def traverse_dir(
13
+ root_dir,
14
+ extensions,
15
+ amount=None,
16
+ str_include=None,
17
+ str_exclude=None,
18
+ is_pure=False,
19
+ is_sort=False,
20
+ is_ext=True):
21
+
22
+ file_list = []
23
+ cnt = 0
24
+ for root, _, files in os.walk(root_dir):
25
+ for file in files:
26
+ if any([file.endswith(f".{ext}") for ext in extensions]):
27
+ # path
28
+ mix_path = os.path.join(root, file)
29
+ pure_path = mix_path[len(root_dir)+1:] if is_pure else mix_path
30
+
31
+ # amount
32
+ if (amount is not None) and (cnt == amount):
33
+ if is_sort:
34
+ file_list.sort()
35
+ return file_list
36
+
37
+ # check string
38
+ if (str_include is not None) and (str_include not in pure_path):
39
+ continue
40
+ if (str_exclude is not None) and (str_exclude in pure_path):
41
+ continue
42
+
43
+ if not is_ext:
44
+ ext = pure_path.split('.')[-1]
45
+ pure_path = pure_path[:-(len(ext)+1)]
46
+ file_list.append(pure_path)
47
+ cnt += 1
48
+ if is_sort:
49
+ file_list.sort()
50
+ return file_list
51
+
52
+
53
+ def get_data_loaders(args, whole_audio=False):
54
+ data_train = AudioDataset(
55
+ filelists = args.data.training_files,
56
+ waveform_sec=args.data.duration,
57
+ hop_size=args.data.block_size,
58
+ sample_rate=args.data.sampling_rate,
59
+ load_all_data=args.train.cache_all_data,
60
+ whole_audio=whole_audio,
61
+ extensions=args.data.extensions,
62
+ n_spk=args.model.n_spk,
63
+ spk=args.spk,
64
+ device=args.train.cache_device,
65
+ fp16=args.train.cache_fp16,
66
+ use_aug=True)
67
+ loader_train = torch.utils.data.DataLoader(
68
+ data_train ,
69
+ batch_size=args.train.batch_size if not whole_audio else 1,
70
+ shuffle=True,
71
+ num_workers=args.train.num_workers if args.train.cache_device=='cpu' else 0,
72
+ persistent_workers=(args.train.num_workers > 0) if args.train.cache_device=='cpu' else False,
73
+ pin_memory=True if args.train.cache_device=='cpu' else False
74
+ )
75
+ data_valid = AudioDataset(
76
+ filelists = args.data.validation_files,
77
+ waveform_sec=args.data.duration,
78
+ hop_size=args.data.block_size,
79
+ sample_rate=args.data.sampling_rate,
80
+ load_all_data=args.train.cache_all_data,
81
+ whole_audio=True,
82
+ spk=args.spk,
83
+ extensions=args.data.extensions,
84
+ n_spk=args.model.n_spk)
85
+ loader_valid = torch.utils.data.DataLoader(
86
+ data_valid,
87
+ batch_size=1,
88
+ shuffle=False,
89
+ num_workers=0,
90
+ pin_memory=True
91
+ )
92
+ return loader_train, loader_valid
93
+
94
+
95
+ class AudioDataset(Dataset):
96
+ def __init__(
97
+ self,
98
+ filelists,
99
+ waveform_sec,
100
+ hop_size,
101
+ sample_rate,
102
+ spk,
103
+ load_all_data=True,
104
+ whole_audio=False,
105
+ extensions=['wav'],
106
+ n_spk=1,
107
+ device='cpu',
108
+ fp16=False,
109
+ use_aug=False,
110
+ ):
111
+ super().__init__()
112
+
113
+ self.waveform_sec = waveform_sec
114
+ self.sample_rate = sample_rate
115
+ self.hop_size = hop_size
116
+ self.filelists = filelists
117
+ self.whole_audio = whole_audio
118
+ self.use_aug = use_aug
119
+ self.data_buffer={}
120
+ self.pitch_aug_dict = {}
121
+ # np.load(os.path.join(self.path_root, 'pitch_aug_dict.npy'), allow_pickle=True).item()
122
+ if load_all_data:
123
+ print('Load all the data filelists:', filelists)
124
+ else:
125
+ print('Load the f0, volume data filelists:', filelists)
126
+ with open(filelists,"r") as f:
127
+ self.paths = f.read().splitlines()
128
+ for name_ext in tqdm(self.paths, total=len(self.paths)):
129
+ name = os.path.splitext(name_ext)[0]
130
+ path_audio = name_ext
131
+ duration = librosa.get_duration(filename = path_audio, sr = self.sample_rate)
132
+
133
+ path_f0 = name_ext + ".f0.npy"
134
+ f0,_ = np.load(path_f0,allow_pickle=True)
135
+ f0 = torch.from_numpy(np.array(f0,dtype=float)).float().unsqueeze(-1).to(device)
136
+
137
+ path_volume = name_ext + ".vol.npy"
138
+ volume = np.load(path_volume)
139
+ volume = torch.from_numpy(volume).float().unsqueeze(-1).to(device)
140
+
141
+ path_augvol = name_ext + ".aug_vol.npy"
142
+ aug_vol = np.load(path_augvol)
143
+ aug_vol = torch.from_numpy(aug_vol).float().unsqueeze(-1).to(device)
144
+
145
+ if n_spk is not None and n_spk > 1:
146
+ spk_name = name_ext.split("/")[-2]
147
+ spk_id = spk[spk_name] if spk_name in spk else 0
148
+ if spk_id < 0 or spk_id >= n_spk:
149
+ raise ValueError(' [x] Muiti-speaker traing error : spk_id must be a positive integer from 0 to n_spk-1 ')
150
+ else:
151
+ spk_id = 0
152
+ spk_id = torch.LongTensor(np.array([spk_id])).to(device)
153
+
154
+ if load_all_data:
155
+ '''
156
+ audio, sr = librosa.load(path_audio, sr=self.sample_rate)
157
+ if len(audio.shape) > 1:
158
+ audio = librosa.to_mono(audio)
159
+ audio = torch.from_numpy(audio).to(device)
160
+ '''
161
+ path_mel = name_ext + ".mel.npy"
162
+ mel = np.load(path_mel)
163
+ mel = torch.from_numpy(mel).to(device)
164
+
165
+ path_augmel = name_ext + ".aug_mel.npy"
166
+ aug_mel,keyshift = np.load(path_augmel, allow_pickle=True)
167
+ aug_mel = np.array(aug_mel,dtype=float)
168
+ aug_mel = torch.from_numpy(aug_mel).to(device)
169
+ self.pitch_aug_dict[name_ext] = keyshift
170
+
171
+ path_units = name_ext + ".soft.pt"
172
+ units = torch.load(path_units).to(device)
173
+ units = units[0]
174
+ units = repeat_expand_2d(units,f0.size(0)).transpose(0,1)
175
+
176
+ if fp16:
177
+ mel = mel.half()
178
+ aug_mel = aug_mel.half()
179
+ units = units.half()
180
+
181
+ self.data_buffer[name_ext] = {
182
+ 'duration': duration,
183
+ 'mel': mel,
184
+ 'aug_mel': aug_mel,
185
+ 'units': units,
186
+ 'f0': f0,
187
+ 'volume': volume,
188
+ 'aug_vol': aug_vol,
189
+ 'spk_id': spk_id
190
+ }
191
+ else:
192
+ path_augmel = name_ext + ".aug_mel.npy"
193
+ aug_mel,keyshift = np.load(path_augmel, allow_pickle=True)
194
+ self.pitch_aug_dict[name_ext] = keyshift
195
+ self.data_buffer[name_ext] = {
196
+ 'duration': duration,
197
+ 'f0': f0,
198
+ 'volume': volume,
199
+ 'aug_vol': aug_vol,
200
+ 'spk_id': spk_id
201
+ }
202
+
203
+
204
+ def __getitem__(self, file_idx):
205
+ name_ext = self.paths[file_idx]
206
+ data_buffer = self.data_buffer[name_ext]
207
+ # check duration. if too short, then skip
208
+ if data_buffer['duration'] < (self.waveform_sec + 0.1):
209
+ return self.__getitem__( (file_idx + 1) % len(self.paths))
210
+
211
+ # get item
212
+ return self.get_data(name_ext, data_buffer)
213
+
214
+ def get_data(self, name_ext, data_buffer):
215
+ name = os.path.splitext(name_ext)[0]
216
+ frame_resolution = self.hop_size / self.sample_rate
217
+ duration = data_buffer['duration']
218
+ waveform_sec = duration if self.whole_audio else self.waveform_sec
219
+
220
+ # load audio
221
+ idx_from = 0 if self.whole_audio else random.uniform(0, duration - waveform_sec - 0.1)
222
+ start_frame = int(idx_from / frame_resolution)
223
+ units_frame_len = int(waveform_sec / frame_resolution)
224
+ aug_flag = random.choice([True, False]) and self.use_aug
225
+ '''
226
+ audio = data_buffer.get('audio')
227
+ if audio is None:
228
+ path_audio = os.path.join(self.path_root, 'audio', name) + '.wav'
229
+ audio, sr = librosa.load(
230
+ path_audio,
231
+ sr = self.sample_rate,
232
+ offset = start_frame * frame_resolution,
233
+ duration = waveform_sec)
234
+ if len(audio.shape) > 1:
235
+ audio = librosa.to_mono(audio)
236
+ # clip audio into N seconds
237
+ audio = audio[ : audio.shape[-1] // self.hop_size * self.hop_size]
238
+ audio = torch.from_numpy(audio).float()
239
+ else:
240
+ audio = audio[start_frame * self.hop_size : (start_frame + units_frame_len) * self.hop_size]
241
+ '''
242
+ # load mel
243
+ mel_key = 'aug_mel' if aug_flag else 'mel'
244
+ mel = data_buffer.get(mel_key)
245
+ if mel is None:
246
+ mel = name_ext + ".mel.npy"
247
+ mel = np.load(mel)
248
+ mel = mel[start_frame : start_frame + units_frame_len]
249
+ mel = torch.from_numpy(mel).float()
250
+ else:
251
+ mel = mel[start_frame : start_frame + units_frame_len]
252
+
253
+ # load f0
254
+ f0 = data_buffer.get('f0')
255
+ aug_shift = 0
256
+ if aug_flag:
257
+ aug_shift = self.pitch_aug_dict[name_ext]
258
+ f0_frames = 2 ** (aug_shift / 12) * f0[start_frame : start_frame + units_frame_len]
259
+
260
+ # load units
261
+ units = data_buffer.get('units')
262
+ if units is None:
263
+ path_units = name_ext + ".soft.pt"
264
+ units = torch.load(path_units)
265
+ units = units[0]
266
+ units = repeat_expand_2d(units,f0.size(0)).transpose(0,1)
267
+
268
+ units = units[start_frame : start_frame + units_frame_len]
269
+
270
+ # load volume
271
+ vol_key = 'aug_vol' if aug_flag else 'volume'
272
+ volume = data_buffer.get(vol_key)
273
+ volume_frames = volume[start_frame : start_frame + units_frame_len]
274
+
275
+ # load spk_id
276
+ spk_id = data_buffer.get('spk_id')
277
+
278
+ # load shift
279
+ aug_shift = torch.from_numpy(np.array([[aug_shift]])).float()
280
+
281
+ return dict(mel=mel, f0=f0_frames, volume=volume_frames, units=units, spk_id=spk_id, aug_shift=aug_shift, name=name, name_ext=name_ext)
282
+
283
+ def __len__(self):
284
+ return len(self.paths)
diffusion/diffusion.py ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import deque
2
+ from functools import partial
3
+ from inspect import isfunction
4
+ import torch.nn.functional as F
5
+ import librosa.sequence
6
+ import numpy as np
7
+ import torch
8
+ from torch import nn
9
+ from tqdm import tqdm
10
+
11
+
12
+ def exists(x):
13
+ return x is not None
14
+
15
+
16
+ def default(val, d):
17
+ if exists(val):
18
+ return val
19
+ return d() if isfunction(d) else d
20
+
21
+
22
+ def extract(a, t, x_shape):
23
+ b, *_ = t.shape
24
+ out = a.gather(-1, t)
25
+ return out.reshape(b, *((1,) * (len(x_shape) - 1)))
26
+
27
+
28
+ def noise_like(shape, device, repeat=False):
29
+ repeat_noise = lambda: torch.randn((1, *shape[1:]), device=device).repeat(shape[0], *((1,) * (len(shape) - 1)))
30
+ noise = lambda: torch.randn(shape, device=device)
31
+ return repeat_noise() if repeat else noise()
32
+
33
+
34
+ def linear_beta_schedule(timesteps, max_beta=0.02):
35
+ """
36
+ linear schedule
37
+ """
38
+ betas = np.linspace(1e-4, max_beta, timesteps)
39
+ return betas
40
+
41
+
42
+ def cosine_beta_schedule(timesteps, s=0.008):
43
+ """
44
+ cosine schedule
45
+ as proposed in https://openreview.net/forum?id=-NEXDKk8gZ
46
+ """
47
+ steps = timesteps + 1
48
+ x = np.linspace(0, steps, steps)
49
+ alphas_cumprod = np.cos(((x / steps) + s) / (1 + s) * np.pi * 0.5) ** 2
50
+ alphas_cumprod = alphas_cumprod / alphas_cumprod[0]
51
+ betas = 1 - (alphas_cumprod[1:] / alphas_cumprod[:-1])
52
+ return np.clip(betas, a_min=0, a_max=0.999)
53
+
54
+
55
+ beta_schedule = {
56
+ "cosine": cosine_beta_schedule,
57
+ "linear": linear_beta_schedule,
58
+ }
59
+
60
+
61
+ class GaussianDiffusion(nn.Module):
62
+ def __init__(self,
63
+ denoise_fn,
64
+ out_dims=128,
65
+ timesteps=1000,
66
+ k_step=1000,
67
+ max_beta=0.02,
68
+ spec_min=-12,
69
+ spec_max=2):
70
+ super().__init__()
71
+ self.denoise_fn = denoise_fn
72
+ self.out_dims = out_dims
73
+ betas = beta_schedule['linear'](timesteps, max_beta=max_beta)
74
+
75
+ alphas = 1. - betas
76
+ alphas_cumprod = np.cumprod(alphas, axis=0)
77
+ alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1])
78
+
79
+ timesteps, = betas.shape
80
+ self.num_timesteps = int(timesteps)
81
+ self.k_step = k_step
82
+
83
+ self.noise_list = deque(maxlen=4)
84
+
85
+ to_torch = partial(torch.tensor, dtype=torch.float32)
86
+
87
+ self.register_buffer('betas', to_torch(betas))
88
+ self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
89
+ self.register_buffer('alphas_cumprod_prev', to_torch(alphas_cumprod_prev))
90
+
91
+ # calculations for diffusion q(x_t | x_{t-1}) and others
92
+ self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod)))
93
+ self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod)))
94
+ self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod)))
95
+ self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod)))
96
+ self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod - 1)))
97
+
98
+ # calculations for posterior q(x_{t-1} | x_t, x_0)
99
+ posterior_variance = betas * (1. - alphas_cumprod_prev) / (1. - alphas_cumprod)
100
+ # above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t)
101
+ self.register_buffer('posterior_variance', to_torch(posterior_variance))
102
+ # below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain
103
+ self.register_buffer('posterior_log_variance_clipped', to_torch(np.log(np.maximum(posterior_variance, 1e-20))))
104
+ self.register_buffer('posterior_mean_coef1', to_torch(
105
+ betas * np.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod)))
106
+ self.register_buffer('posterior_mean_coef2', to_torch(
107
+ (1. - alphas_cumprod_prev) * np.sqrt(alphas) / (1. - alphas_cumprod)))
108
+
109
+ self.register_buffer('spec_min', torch.FloatTensor([spec_min])[None, None, :out_dims])
110
+ self.register_buffer('spec_max', torch.FloatTensor([spec_max])[None, None, :out_dims])
111
+
112
+ def q_mean_variance(self, x_start, t):
113
+ mean = extract(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start
114
+ variance = extract(1. - self.alphas_cumprod, t, x_start.shape)
115
+ log_variance = extract(self.log_one_minus_alphas_cumprod, t, x_start.shape)
116
+ return mean, variance, log_variance
117
+
118
+ def predict_start_from_noise(self, x_t, t, noise):
119
+ return (
120
+ extract(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t -
121
+ extract(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise
122
+ )
123
+
124
+ def q_posterior(self, x_start, x_t, t):
125
+ posterior_mean = (
126
+ extract(self.posterior_mean_coef1, t, x_t.shape) * x_start +
127
+ extract(self.posterior_mean_coef2, t, x_t.shape) * x_t
128
+ )
129
+ posterior_variance = extract(self.posterior_variance, t, x_t.shape)
130
+ posterior_log_variance_clipped = extract(self.posterior_log_variance_clipped, t, x_t.shape)
131
+ return posterior_mean, posterior_variance, posterior_log_variance_clipped
132
+
133
+ def p_mean_variance(self, x, t, cond):
134
+ noise_pred = self.denoise_fn(x, t, cond=cond)
135
+ x_recon = self.predict_start_from_noise(x, t=t, noise=noise_pred)
136
+
137
+ x_recon.clamp_(-1., 1.)
138
+
139
+ model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)
140
+ return model_mean, posterior_variance, posterior_log_variance
141
+
142
+ @torch.no_grad()
143
+ def p_sample(self, x, t, cond, clip_denoised=True, repeat_noise=False):
144
+ b, *_, device = *x.shape, x.device
145
+ model_mean, _, model_log_variance = self.p_mean_variance(x=x, t=t, cond=cond)
146
+ noise = noise_like(x.shape, device, repeat_noise)
147
+ # no noise when t == 0
148
+ nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
149
+ return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
150
+
151
+ @torch.no_grad()
152
+ def p_sample_plms(self, x, t, interval, cond, clip_denoised=True, repeat_noise=False):
153
+ """
154
+ Use the PLMS method from
155
+ [Pseudo Numerical Methods for Diffusion Models on Manifolds](https://arxiv.org/abs/2202.09778).
156
+ """
157
+
158
+ def get_x_pred(x, noise_t, t):
159
+ a_t = extract(self.alphas_cumprod, t, x.shape)
160
+ a_prev = extract(self.alphas_cumprod, torch.max(t - interval, torch.zeros_like(t)), x.shape)
161
+ a_t_sq, a_prev_sq = a_t.sqrt(), a_prev.sqrt()
162
+
163
+ x_delta = (a_prev - a_t) * ((1 / (a_t_sq * (a_t_sq + a_prev_sq))) * x - 1 / (
164
+ a_t_sq * (((1 - a_prev) * a_t).sqrt() + ((1 - a_t) * a_prev).sqrt())) * noise_t)
165
+ x_pred = x + x_delta
166
+
167
+ return x_pred
168
+
169
+ noise_list = self.noise_list
170
+ noise_pred = self.denoise_fn(x, t, cond=cond)
171
+
172
+ if len(noise_list) == 0:
173
+ x_pred = get_x_pred(x, noise_pred, t)
174
+ noise_pred_prev = self.denoise_fn(x_pred, max(t - interval, 0), cond=cond)
175
+ noise_pred_prime = (noise_pred + noise_pred_prev) / 2
176
+ elif len(noise_list) == 1:
177
+ noise_pred_prime = (3 * noise_pred - noise_list[-1]) / 2
178
+ elif len(noise_list) == 2:
179
+ noise_pred_prime = (23 * noise_pred - 16 * noise_list[-1] + 5 * noise_list[-2]) / 12
180
+ else:
181
+ noise_pred_prime = (55 * noise_pred - 59 * noise_list[-1] + 37 * noise_list[-2] - 9 * noise_list[-3]) / 24
182
+
183
+ x_prev = get_x_pred(x, noise_pred_prime, t)
184
+ noise_list.append(noise_pred)
185
+
186
+ return x_prev
187
+
188
+ def q_sample(self, x_start, t, noise=None):
189
+ noise = default(noise, lambda: torch.randn_like(x_start))
190
+ return (
191
+ extract(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start +
192
+ extract(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise
193
+ )
194
+
195
+ def p_losses(self, x_start, t, cond, noise=None, loss_type='l2'):
196
+ noise = default(noise, lambda: torch.randn_like(x_start))
197
+
198
+ x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
199
+ x_recon = self.denoise_fn(x_noisy, t, cond)
200
+
201
+ if loss_type == 'l1':
202
+ loss = (noise - x_recon).abs().mean()
203
+ elif loss_type == 'l2':
204
+ loss = F.mse_loss(noise, x_recon)
205
+ else:
206
+ raise NotImplementedError()
207
+
208
+ return loss
209
+
210
+ def forward(self,
211
+ condition,
212
+ gt_spec=None,
213
+ infer=True,
214
+ infer_speedup=10,
215
+ method='dpm-solver',
216
+ k_step=300,
217
+ use_tqdm=True):
218
+ """
219
+ conditioning diffusion, use fastspeech2 encoder output as the condition
220
+ """
221
+ cond = condition.transpose(1, 2)
222
+ b, device = condition.shape[0], condition.device
223
+
224
+ if not infer:
225
+ spec = self.norm_spec(gt_spec)
226
+ t = torch.randint(0, self.k_step, (b,), device=device).long()
227
+ norm_spec = spec.transpose(1, 2)[:, None, :, :] # [B, 1, M, T]
228
+ return self.p_losses(norm_spec, t, cond=cond)
229
+ else:
230
+ shape = (cond.shape[0], 1, self.out_dims, cond.shape[2])
231
+
232
+ if gt_spec is None:
233
+ t = self.k_step
234
+ x = torch.randn(shape, device=device)
235
+ else:
236
+ t = k_step
237
+ norm_spec = self.norm_spec(gt_spec)
238
+ norm_spec = norm_spec.transpose(1, 2)[:, None, :, :]
239
+ x = self.q_sample(x_start=norm_spec, t=torch.tensor([t - 1], device=device).long())
240
+
241
+ if method is not None and infer_speedup > 1:
242
+ if method == 'dpm-solver':
243
+ from .dpm_solver_pytorch import NoiseScheduleVP, model_wrapper, DPM_Solver
244
+ # 1. Define the noise schedule.
245
+ noise_schedule = NoiseScheduleVP(schedule='discrete', betas=self.betas[:t])
246
+
247
+ # 2. Convert your discrete-time `model` to the continuous-time
248
+ # noise prediction model. Here is an example for a diffusion model
249
+ # `model` with the noise prediction type ("noise") .
250
+ def my_wrapper(fn):
251
+ def wrapped(x, t, **kwargs):
252
+ ret = fn(x, t, **kwargs)
253
+ if use_tqdm:
254
+ self.bar.update(1)
255
+ return ret
256
+
257
+ return wrapped
258
+
259
+ model_fn = model_wrapper(
260
+ my_wrapper(self.denoise_fn),
261
+ noise_schedule,
262
+ model_type="noise", # or "x_start" or "v" or "score"
263
+ model_kwargs={"cond": cond}
264
+ )
265
+
266
+ # 3. Define dpm-solver and sample by singlestep DPM-Solver.
267
+ # (We recommend singlestep DPM-Solver for unconditional sampling)
268
+ # You can adjust the `steps` to balance the computation
269
+ # costs and the sample quality.
270
+ dpm_solver = DPM_Solver(model_fn, noise_schedule)
271
+
272
+ steps = t // infer_speedup
273
+ if use_tqdm:
274
+ self.bar = tqdm(desc="sample time step", total=steps)
275
+ x = dpm_solver.sample(
276
+ x,
277
+ steps=steps,
278
+ order=3,
279
+ skip_type="time_uniform",
280
+ method="singlestep",
281
+ )
282
+ if use_tqdm:
283
+ self.bar.close()
284
+ elif method == 'pndm':
285
+ self.noise_list = deque(maxlen=4)
286
+ if use_tqdm:
287
+ for i in tqdm(
288
+ reversed(range(0, t, infer_speedup)), desc='sample time step',
289
+ total=t // infer_speedup,
290
+ ):
291
+ x = self.p_sample_plms(
292
+ x, torch.full((b,), i, device=device, dtype=torch.long),
293
+ infer_speedup, cond=cond
294
+ )
295
+ else:
296
+ for i in reversed(range(0, t, infer_speedup)):
297
+ x = self.p_sample_plms(
298
+ x, torch.full((b,), i, device=device, dtype=torch.long),
299
+ infer_speedup, cond=cond
300
+ )
301
+ else:
302
+ raise NotImplementedError(method)
303
+ else:
304
+ if use_tqdm:
305
+ for i in tqdm(reversed(range(0, t)), desc='sample time step', total=t):
306
+ x = self.p_sample(x, torch.full((b,), i, device=device, dtype=torch.long), cond)
307
+ else:
308
+ for i in reversed(range(0, t)):
309
+ x = self.p_sample(x, torch.full((b,), i, device=device, dtype=torch.long), cond)
310
+ x = x.squeeze(1).transpose(1, 2) # [B, T, M]
311
+ return self.denorm_spec(x)
312
+
313
+ def norm_spec(self, x):
314
+ return (x - self.spec_min) / (self.spec_max - self.spec_min) * 2 - 1
315
+
316
+ def denorm_spec(self, x):
317
+ return (x + 1) / 2 * (self.spec_max - self.spec_min) + self.spec_min
diffusion/diffusion_onnx.py ADDED
@@ -0,0 +1,612 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import deque
2
+ from functools import partial
3
+ from inspect import isfunction
4
+ import torch.nn.functional as F
5
+ import librosa.sequence
6
+ import numpy as np
7
+ from torch.nn import Conv1d
8
+ from torch.nn import Mish
9
+ import torch
10
+ from torch import nn
11
+ from tqdm import tqdm
12
+ import math
13
+
14
+
15
+ def exists(x):
16
+ return x is not None
17
+
18
+
19
+ def default(val, d):
20
+ if exists(val):
21
+ return val
22
+ return d() if isfunction(d) else d
23
+
24
+
25
+ def extract(a, t):
26
+ return a[t].reshape((1, 1, 1, 1))
27
+
28
+
29
+ def noise_like(shape, device, repeat=False):
30
+ repeat_noise = lambda: torch.randn((1, *shape[1:]), device=device).repeat(shape[0], *((1,) * (len(shape) - 1)))
31
+ noise = lambda: torch.randn(shape, device=device)
32
+ return repeat_noise() if repeat else noise()
33
+
34
+
35
+ def linear_beta_schedule(timesteps, max_beta=0.02):
36
+ """
37
+ linear schedule
38
+ """
39
+ betas = np.linspace(1e-4, max_beta, timesteps)
40
+ return betas
41
+
42
+
43
+ def cosine_beta_schedule(timesteps, s=0.008):
44
+ """
45
+ cosine schedule
46
+ as proposed in https://openreview.net/forum?id=-NEXDKk8gZ
47
+ """
48
+ steps = timesteps + 1
49
+ x = np.linspace(0, steps, steps)
50
+ alphas_cumprod = np.cos(((x / steps) + s) / (1 + s) * np.pi * 0.5) ** 2
51
+ alphas_cumprod = alphas_cumprod / alphas_cumprod[0]
52
+ betas = 1 - (alphas_cumprod[1:] / alphas_cumprod[:-1])
53
+ return np.clip(betas, a_min=0, a_max=0.999)
54
+
55
+
56
+ beta_schedule = {
57
+ "cosine": cosine_beta_schedule,
58
+ "linear": linear_beta_schedule,
59
+ }
60
+
61
+
62
+ def extract_1(a, t):
63
+ return a[t].reshape((1, 1, 1, 1))
64
+
65
+
66
+ def predict_stage0(noise_pred, noise_pred_prev):
67
+ return (noise_pred + noise_pred_prev) / 2
68
+
69
+
70
+ def predict_stage1(noise_pred, noise_list):
71
+ return (noise_pred * 3
72
+ - noise_list[-1]) / 2
73
+
74
+
75
+ def predict_stage2(noise_pred, noise_list):
76
+ return (noise_pred * 23
77
+ - noise_list[-1] * 16
78
+ + noise_list[-2] * 5) / 12
79
+
80
+
81
+ def predict_stage3(noise_pred, noise_list):
82
+ return (noise_pred * 55
83
+ - noise_list[-1] * 59
84
+ + noise_list[-2] * 37
85
+ - noise_list[-3] * 9) / 24
86
+
87
+
88
+ class SinusoidalPosEmb(nn.Module):
89
+ def __init__(self, dim):
90
+ super().__init__()
91
+ self.dim = dim
92
+ self.half_dim = dim // 2
93
+ self.emb = 9.21034037 / (self.half_dim - 1)
94
+ self.emb = torch.exp(torch.arange(self.half_dim) * torch.tensor(-self.emb)).unsqueeze(0)
95
+ self.emb = self.emb.cpu()
96
+
97
+ def forward(self, x):
98
+ emb = self.emb * x
99
+ emb = torch.cat((emb.sin(), emb.cos()), dim=-1)
100
+ return emb
101
+
102
+
103
+ class ResidualBlock(nn.Module):
104
+ def __init__(self, encoder_hidden, residual_channels, dilation):
105
+ super().__init__()
106
+ self.residual_channels = residual_channels
107
+ self.dilated_conv = Conv1d(residual_channels, 2 * residual_channels, 3, padding=dilation, dilation=dilation)
108
+ self.diffusion_projection = nn.Linear(residual_channels, residual_channels)
109
+ self.conditioner_projection = Conv1d(encoder_hidden, 2 * residual_channels, 1)
110
+ self.output_projection = Conv1d(residual_channels, 2 * residual_channels, 1)
111
+
112
+ def forward(self, x, conditioner, diffusion_step):
113
+ diffusion_step = self.diffusion_projection(diffusion_step).unsqueeze(-1)
114
+ conditioner = self.conditioner_projection(conditioner)
115
+ y = x + diffusion_step
116
+ y = self.dilated_conv(y) + conditioner
117
+
118
+ gate, filter_1 = torch.split(y, [self.residual_channels, self.residual_channels], dim=1)
119
+
120
+ y = torch.sigmoid(gate) * torch.tanh(filter_1)
121
+ y = self.output_projection(y)
122
+
123
+ residual, skip = torch.split(y, [self.residual_channels, self.residual_channels], dim=1)
124
+
125
+ return (x + residual) / 1.41421356, skip
126
+
127
+
128
+ class DiffNet(nn.Module):
129
+ def __init__(self, in_dims, n_layers, n_chans, n_hidden):
130
+ super().__init__()
131
+ self.encoder_hidden = n_hidden
132
+ self.residual_layers = n_layers
133
+ self.residual_channels = n_chans
134
+ self.input_projection = Conv1d(in_dims, self.residual_channels, 1)
135
+ self.diffusion_embedding = SinusoidalPosEmb(self.residual_channels)
136
+ dim = self.residual_channels
137
+ self.mlp = nn.Sequential(
138
+ nn.Linear(dim, dim * 4),
139
+ Mish(),
140
+ nn.Linear(dim * 4, dim)
141
+ )
142
+ self.residual_layers = nn.ModuleList([
143
+ ResidualBlock(self.encoder_hidden, self.residual_channels, 1)
144
+ for i in range(self.residual_layers)
145
+ ])
146
+ self.skip_projection = Conv1d(self.residual_channels, self.residual_channels, 1)
147
+ self.output_projection = Conv1d(self.residual_channels, in_dims, 1)
148
+ nn.init.zeros_(self.output_projection.weight)
149
+
150
+ def forward(self, spec, diffusion_step, cond):
151
+ x = spec.squeeze(0)
152
+ x = self.input_projection(x) # x [B, residual_channel, T]
153
+ x = F.relu(x)
154
+ # skip = torch.randn_like(x)
155
+ diffusion_step = diffusion_step.float()
156
+ diffusion_step = self.diffusion_embedding(diffusion_step)
157
+ diffusion_step = self.mlp(diffusion_step)
158
+
159
+ x, skip = self.residual_layers[0](x, cond, diffusion_step)
160
+ # noinspection PyTypeChecker
161
+ for layer in self.residual_layers[1:]:
162
+ x, skip_connection = layer.forward(x, cond, diffusion_step)
163
+ skip = skip + skip_connection
164
+ x = skip / math.sqrt(len(self.residual_layers))
165
+ x = self.skip_projection(x)
166
+ x = F.relu(x)
167
+ x = self.output_projection(x) # [B, 80, T]
168
+ return x.unsqueeze(1)
169
+
170
+
171
+ class AfterDiffusion(nn.Module):
172
+ def __init__(self, spec_max, spec_min, v_type='a'):
173
+ super().__init__()
174
+ self.spec_max = spec_max
175
+ self.spec_min = spec_min
176
+ self.type = v_type
177
+
178
+ def forward(self, x):
179
+ x = x.squeeze(1).permute(0, 2, 1)
180
+ mel_out = (x + 1) / 2 * (self.spec_max - self.spec_min) + self.spec_min
181
+ if self.type == 'nsf-hifigan-log10':
182
+ mel_out = mel_out * 0.434294
183
+ return mel_out.transpose(2, 1)
184
+
185
+
186
+ class Pred(nn.Module):
187
+ def __init__(self, alphas_cumprod):
188
+ super().__init__()
189
+ self.alphas_cumprod = alphas_cumprod
190
+
191
+ def forward(self, x_1, noise_t, t_1, t_prev):
192
+ a_t = extract(self.alphas_cumprod, t_1).cpu()
193
+ a_prev = extract(self.alphas_cumprod, t_prev).cpu()
194
+ a_t_sq, a_prev_sq = a_t.sqrt().cpu(), a_prev.sqrt().cpu()
195
+ x_delta = (a_prev - a_t) * ((1 / (a_t_sq * (a_t_sq + a_prev_sq))) * x_1 - 1 / (
196
+ a_t_sq * (((1 - a_prev) * a_t).sqrt() + ((1 - a_t) * a_prev).sqrt())) * noise_t)
197
+ x_pred = x_1 + x_delta.cpu()
198
+
199
+ return x_pred
200
+
201
+
202
+ class GaussianDiffusion(nn.Module):
203
+ def __init__(self,
204
+ out_dims=128,
205
+ n_layers=20,
206
+ n_chans=384,
207
+ n_hidden=256,
208
+ timesteps=1000,
209
+ k_step=1000,
210
+ max_beta=0.02,
211
+ spec_min=-12,
212
+ spec_max=2):
213
+ super().__init__()
214
+ self.denoise_fn = DiffNet(out_dims, n_layers, n_chans, n_hidden)
215
+ self.out_dims = out_dims
216
+ self.mel_bins = out_dims
217
+ self.n_hidden = n_hidden
218
+ betas = beta_schedule['linear'](timesteps, max_beta=max_beta)
219
+
220
+ alphas = 1. - betas
221
+ alphas_cumprod = np.cumprod(alphas, axis=0)
222
+ alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1])
223
+ timesteps, = betas.shape
224
+ self.num_timesteps = int(timesteps)
225
+ self.k_step = k_step
226
+
227
+ self.noise_list = deque(maxlen=4)
228
+
229
+ to_torch = partial(torch.tensor, dtype=torch.float32)
230
+
231
+ self.register_buffer('betas', to_torch(betas))
232
+ self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
233
+ self.register_buffer('alphas_cumprod_prev', to_torch(alphas_cumprod_prev))
234
+
235
+ # calculations for diffusion q(x_t | x_{t-1}) and others
236
+ self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod)))
237
+ self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod)))
238
+ self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod)))
239
+ self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod)))
240
+ self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod - 1)))
241
+
242
+ # calculations for posterior q(x_{t-1} | x_t, x_0)
243
+ posterior_variance = betas * (1. - alphas_cumprod_prev) / (1. - alphas_cumprod)
244
+ # above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t)
245
+ self.register_buffer('posterior_variance', to_torch(posterior_variance))
246
+ # below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain
247
+ self.register_buffer('posterior_log_variance_clipped', to_torch(np.log(np.maximum(posterior_variance, 1e-20))))
248
+ self.register_buffer('posterior_mean_coef1', to_torch(
249
+ betas * np.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod)))
250
+ self.register_buffer('posterior_mean_coef2', to_torch(
251
+ (1. - alphas_cumprod_prev) * np.sqrt(alphas) / (1. - alphas_cumprod)))
252
+
253
+ self.register_buffer('spec_min', torch.FloatTensor([spec_min])[None, None, :out_dims])
254
+ self.register_buffer('spec_max', torch.FloatTensor([spec_max])[None, None, :out_dims])
255
+ self.ad = AfterDiffusion(self.spec_max, self.spec_min)
256
+ self.xp = Pred(self.alphas_cumprod)
257
+
258
+ def q_mean_variance(self, x_start, t):
259
+ mean = extract(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start
260
+ variance = extract(1. - self.alphas_cumprod, t, x_start.shape)
261
+ log_variance = extract(self.log_one_minus_alphas_cumprod, t, x_start.shape)
262
+ return mean, variance, log_variance
263
+
264
+ def predict_start_from_noise(self, x_t, t, noise):
265
+ return (
266
+ extract(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t -
267
+ extract(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise
268
+ )
269
+
270
+ def q_posterior(self, x_start, x_t, t):
271
+ posterior_mean = (
272
+ extract(self.posterior_mean_coef1, t, x_t.shape) * x_start +
273
+ extract(self.posterior_mean_coef2, t, x_t.shape) * x_t
274
+ )
275
+ posterior_variance = extract(self.posterior_variance, t, x_t.shape)
276
+ posterior_log_variance_clipped = extract(self.posterior_log_variance_clipped, t, x_t.shape)
277
+ return posterior_mean, posterior_variance, posterior_log_variance_clipped
278
+
279
+ def p_mean_variance(self, x, t, cond):
280
+ noise_pred = self.denoise_fn(x, t, cond=cond)
281
+ x_recon = self.predict_start_from_noise(x, t=t, noise=noise_pred)
282
+
283
+ x_recon.clamp_(-1., 1.)
284
+
285
+ model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)
286
+ return model_mean, posterior_variance, posterior_log_variance
287
+
288
+ @torch.no_grad()
289
+ def p_sample(self, x, t, cond, clip_denoised=True, repeat_noise=False):
290
+ b, *_, device = *x.shape, x.device
291
+ model_mean, _, model_log_variance = self.p_mean_variance(x=x, t=t, cond=cond)
292
+ noise = noise_like(x.shape, device, repeat_noise)
293
+ # no noise when t == 0
294
+ nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
295
+ return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
296
+
297
+ @torch.no_grad()
298
+ def p_sample_plms(self, x, t, interval, cond, clip_denoised=True, repeat_noise=False):
299
+ """
300
+ Use the PLMS method from
301
+ [Pseudo Numerical Methods for Diffusion Models on Manifolds](https://arxiv.org/abs/2202.09778).
302
+ """
303
+
304
+ def get_x_pred(x, noise_t, t):
305
+ a_t = extract(self.alphas_cumprod, t)
306
+ a_prev = extract(self.alphas_cumprod, torch.max(t - interval, torch.zeros_like(t)))
307
+ a_t_sq, a_prev_sq = a_t.sqrt(), a_prev.sqrt()
308
+
309
+ x_delta = (a_prev - a_t) * ((1 / (a_t_sq * (a_t_sq + a_prev_sq))) * x - 1 / (
310
+ a_t_sq * (((1 - a_prev) * a_t).sqrt() + ((1 - a_t) * a_prev).sqrt())) * noise_t)
311
+ x_pred = x + x_delta
312
+
313
+ return x_pred
314
+
315
+ noise_list = self.noise_list
316
+ noise_pred = self.denoise_fn(x, t, cond=cond)
317
+
318
+ if len(noise_list) == 0:
319
+ x_pred = get_x_pred(x, noise_pred, t)
320
+ noise_pred_prev = self.denoise_fn(x_pred, max(t - interval, 0), cond=cond)
321
+ noise_pred_prime = (noise_pred + noise_pred_prev) / 2
322
+ elif len(noise_list) == 1:
323
+ noise_pred_prime = (3 * noise_pred - noise_list[-1]) / 2
324
+ elif len(noise_list) == 2:
325
+ noise_pred_prime = (23 * noise_pred - 16 * noise_list[-1] + 5 * noise_list[-2]) / 12
326
+ else:
327
+ noise_pred_prime = (55 * noise_pred - 59 * noise_list[-1] + 37 * noise_list[-2] - 9 * noise_list[-3]) / 24
328
+
329
+ x_prev = get_x_pred(x, noise_pred_prime, t)
330
+ noise_list.append(noise_pred)
331
+
332
+ return x_prev
333
+
334
+ def q_sample(self, x_start, t, noise=None):
335
+ noise = default(noise, lambda: torch.randn_like(x_start))
336
+ return (
337
+ extract(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start +
338
+ extract(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise
339
+ )
340
+
341
+ def p_losses(self, x_start, t, cond, noise=None, loss_type='l2'):
342
+ noise = default(noise, lambda: torch.randn_like(x_start))
343
+
344
+ x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
345
+ x_recon = self.denoise_fn(x_noisy, t, cond)
346
+
347
+ if loss_type == 'l1':
348
+ loss = (noise - x_recon).abs().mean()
349
+ elif loss_type == 'l2':
350
+ loss = F.mse_loss(noise, x_recon)
351
+ else:
352
+ raise NotImplementedError()
353
+
354
+ return loss
355
+
356
+ def org_forward(self,
357
+ condition,
358
+ init_noise=None,
359
+ gt_spec=None,
360
+ infer=True,
361
+ infer_speedup=100,
362
+ method='pndm',
363
+ k_step=1000,
364
+ use_tqdm=True):
365
+ """
366
+ conditioning diffusion, use fastspeech2 encoder output as the condition
367
+ """
368
+ cond = condition
369
+ b, device = condition.shape[0], condition.device
370
+ if not infer:
371
+ spec = self.norm_spec(gt_spec)
372
+ t = torch.randint(0, self.k_step, (b,), device=device).long()
373
+ norm_spec = spec.transpose(1, 2)[:, None, :, :] # [B, 1, M, T]
374
+ return self.p_losses(norm_spec, t, cond=cond)
375
+ else:
376
+ shape = (cond.shape[0], 1, self.out_dims, cond.shape[2])
377
+
378
+ if gt_spec is None:
379
+ t = self.k_step
380
+ if init_noise is None:
381
+ x = torch.randn(shape, device=device)
382
+ else:
383
+ x = init_noise
384
+ else:
385
+ t = k_step
386
+ norm_spec = self.norm_spec(gt_spec)
387
+ norm_spec = norm_spec.transpose(1, 2)[:, None, :, :]
388
+ x = self.q_sample(x_start=norm_spec, t=torch.tensor([t - 1], device=device).long())
389
+
390
+ if method is not None and infer_speedup > 1:
391
+ if method == 'dpm-solver':
392
+ from .dpm_solver_pytorch import NoiseScheduleVP, model_wrapper, DPM_Solver
393
+ # 1. Define the noise schedule.
394
+ noise_schedule = NoiseScheduleVP(schedule='discrete', betas=self.betas[:t])
395
+
396
+ # 2. Convert your discrete-time `model` to the continuous-time
397
+ # noise prediction model. Here is an example for a diffusion model
398
+ # `model` with the noise prediction type ("noise") .
399
+ def my_wrapper(fn):
400
+ def wrapped(x, t, **kwargs):
401
+ ret = fn(x, t, **kwargs)
402
+ if use_tqdm:
403
+ self.bar.update(1)
404
+ return ret
405
+
406
+ return wrapped
407
+
408
+ model_fn = model_wrapper(
409
+ my_wrapper(self.denoise_fn),
410
+ noise_schedule,
411
+ model_type="noise", # or "x_start" or "v" or "score"
412
+ model_kwargs={"cond": cond}
413
+ )
414
+
415
+ # 3. Define dpm-solver and sample by singlestep DPM-Solver.
416
+ # (We recommend singlestep DPM-Solver for unconditional sampling)
417
+ # You can adjust the `steps` to balance the computation
418
+ # costs and the sample quality.
419
+ dpm_solver = DPM_Solver(model_fn, noise_schedule)
420
+
421
+ steps = t // infer_speedup
422
+ if use_tqdm:
423
+ self.bar = tqdm(desc="sample time step", total=steps)
424
+ x = dpm_solver.sample(
425
+ x,
426
+ steps=steps,
427
+ order=3,
428
+ skip_type="time_uniform",
429
+ method="singlestep",
430
+ )
431
+ if use_tqdm:
432
+ self.bar.close()
433
+ elif method == 'pndm':
434
+ self.noise_list = deque(maxlen=4)
435
+ if use_tqdm:
436
+ for i in tqdm(
437
+ reversed(range(0, t, infer_speedup)), desc='sample time step',
438
+ total=t // infer_speedup,
439
+ ):
440
+ x = self.p_sample_plms(
441
+ x, torch.full((b,), i, device=device, dtype=torch.long),
442
+ infer_speedup, cond=cond
443
+ )
444
+ else:
445
+ for i in reversed(range(0, t, infer_speedup)):
446
+ x = self.p_sample_plms(
447
+ x, torch.full((b,), i, device=device, dtype=torch.long),
448
+ infer_speedup, cond=cond
449
+ )
450
+ else:
451
+ raise NotImplementedError(method)
452
+ else:
453
+ if use_tqdm:
454
+ for i in tqdm(reversed(range(0, t)), desc='sample time step', total=t):
455
+ x = self.p_sample(x, torch.full((b,), i, device=device, dtype=torch.long), cond)
456
+ else:
457
+ for i in reversed(range(0, t)):
458
+ x = self.p_sample(x, torch.full((b,), i, device=device, dtype=torch.long), cond)
459
+ x = x.squeeze(1).transpose(1, 2) # [B, T, M]
460
+ return self.denorm_spec(x).transpose(2, 1)
461
+
462
+ def norm_spec(self, x):
463
+ return (x - self.spec_min) / (self.spec_max - self.spec_min) * 2 - 1
464
+
465
+ def denorm_spec(self, x):
466
+ return (x + 1) / 2 * (self.spec_max - self.spec_min) + self.spec_min
467
+
468
+ def get_x_pred(self, x_1, noise_t, t_1, t_prev):
469
+ a_t = extract(self.alphas_cumprod, t_1)
470
+ a_prev = extract(self.alphas_cumprod, t_prev)
471
+ a_t_sq, a_prev_sq = a_t.sqrt(), a_prev.sqrt()
472
+ x_delta = (a_prev - a_t) * ((1 / (a_t_sq * (a_t_sq + a_prev_sq))) * x_1 - 1 / (
473
+ a_t_sq * (((1 - a_prev) * a_t).sqrt() + ((1 - a_t) * a_prev).sqrt())) * noise_t)
474
+ x_pred = x_1 + x_delta
475
+ return x_pred
476
+
477
+ def OnnxExport(self, project_name=None, init_noise=None, hidden_channels=256, export_denoise=True, export_pred=True, export_after=True):
478
+ cond = torch.randn([1, self.n_hidden, 10]).cpu()
479
+ if init_noise is None:
480
+ x = torch.randn((1, 1, self.mel_bins, cond.shape[2]), dtype=torch.float32).cpu()
481
+ else:
482
+ x = init_noise
483
+ pndms = 100
484
+
485
+ org_y_x = self.org_forward(cond, init_noise=x)
486
+
487
+ device = cond.device
488
+ n_frames = cond.shape[2]
489
+ step_range = torch.arange(0, self.k_step, pndms, dtype=torch.long, device=device).flip(0)
490
+ plms_noise_stage = torch.tensor(0, dtype=torch.long, device=device)
491
+ noise_list = torch.zeros((0, 1, 1, self.mel_bins, n_frames), device=device)
492
+
493
+ ot = step_range[0]
494
+ ot_1 = torch.full((1,), ot, device=device, dtype=torch.long)
495
+ if export_denoise:
496
+ torch.onnx.export(
497
+ self.denoise_fn,
498
+ (x.cpu(), ot_1.cpu(), cond.cpu()),
499
+ f"{project_name}_denoise.onnx",
500
+ input_names=["noise", "time", "condition"],
501
+ output_names=["noise_pred"],
502
+ dynamic_axes={
503
+ "noise": [3],
504
+ "condition": [2]
505
+ },
506
+ opset_version=16
507
+ )
508
+
509
+ for t in step_range:
510
+ t_1 = torch.full((1,), t, device=device, dtype=torch.long)
511
+ noise_pred = self.denoise_fn(x, t_1, cond)
512
+ t_prev = t_1 - pndms
513
+ t_prev = t_prev * (t_prev > 0)
514
+ if plms_noise_stage == 0:
515
+ if export_pred:
516
+ torch.onnx.export(
517
+ self.xp,
518
+ (x.cpu(), noise_pred.cpu(), t_1.cpu(), t_prev.cpu()),
519
+ f"{project_name}_pred.onnx",
520
+ input_names=["noise", "noise_pred", "time", "time_prev"],
521
+ output_names=["noise_pred_o"],
522
+ dynamic_axes={
523
+ "noise": [3],
524
+ "noise_pred": [3]
525
+ },
526
+ opset_version=16
527
+ )
528
+
529
+ x_pred = self.get_x_pred(x, noise_pred, t_1, t_prev)
530
+ noise_pred_prev = self.denoise_fn(x_pred, t_prev, cond=cond)
531
+ noise_pred_prime = predict_stage0(noise_pred, noise_pred_prev)
532
+
533
+ elif plms_noise_stage == 1:
534
+ noise_pred_prime = predict_stage1(noise_pred, noise_list)
535
+
536
+ elif plms_noise_stage == 2:
537
+ noise_pred_prime = predict_stage2(noise_pred, noise_list)
538
+
539
+ else:
540
+ noise_pred_prime = predict_stage3(noise_pred, noise_list)
541
+
542
+ noise_pred = noise_pred.unsqueeze(0)
543
+
544
+ if plms_noise_stage < 3:
545
+ noise_list = torch.cat((noise_list, noise_pred), dim=0)
546
+ plms_noise_stage = plms_noise_stage + 1
547
+
548
+ else:
549
+ noise_list = torch.cat((noise_list[-2:], noise_pred), dim=0)
550
+
551
+ x = self.get_x_pred(x, noise_pred_prime, t_1, t_prev)
552
+ if export_after:
553
+ torch.onnx.export(
554
+ self.ad,
555
+ x.cpu(),
556
+ f"{project_name}_after.onnx",
557
+ input_names=["x"],
558
+ output_names=["mel_out"],
559
+ dynamic_axes={
560
+ "x": [3]
561
+ },
562
+ opset_version=16
563
+ )
564
+ x = self.ad(x)
565
+
566
+ print((x == org_y_x).all())
567
+ return x
568
+
569
+ def forward(self, condition=None, init_noise=None, pndms=None, k_step=None):
570
+ cond = condition
571
+ x = init_noise
572
+
573
+ device = cond.device
574
+ n_frames = cond.shape[2]
575
+ step_range = torch.arange(0, k_step.item(), pndms.item(), dtype=torch.long, device=device).flip(0)
576
+ plms_noise_stage = torch.tensor(0, dtype=torch.long, device=device)
577
+ noise_list = torch.zeros((0, 1, 1, self.mel_bins, n_frames), device=device)
578
+
579
+ ot = step_range[0]
580
+ ot_1 = torch.full((1,), ot, device=device, dtype=torch.long)
581
+
582
+ for t in step_range:
583
+ t_1 = torch.full((1,), t, device=device, dtype=torch.long)
584
+ noise_pred = self.denoise_fn(x, t_1, cond)
585
+ t_prev = t_1 - pndms
586
+ t_prev = t_prev * (t_prev > 0)
587
+ if plms_noise_stage == 0:
588
+ x_pred = self.get_x_pred(x, noise_pred, t_1, t_prev)
589
+ noise_pred_prev = self.denoise_fn(x_pred, t_prev, cond=cond)
590
+ noise_pred_prime = predict_stage0(noise_pred, noise_pred_prev)
591
+
592
+ elif plms_noise_stage == 1:
593
+ noise_pred_prime = predict_stage1(noise_pred, noise_list)
594
+
595
+ elif plms_noise_stage == 2:
596
+ noise_pred_prime = predict_stage2(noise_pred, noise_list)
597
+
598
+ else:
599
+ noise_pred_prime = predict_stage3(noise_pred, noise_list)
600
+
601
+ noise_pred = noise_pred.unsqueeze(0)
602
+
603
+ if plms_noise_stage < 3:
604
+ noise_list = torch.cat((noise_list, noise_pred), dim=0)
605
+ plms_noise_stage = plms_noise_stage + 1
606
+
607
+ else:
608
+ noise_list = torch.cat((noise_list[-2:], noise_pred), dim=0)
609
+
610
+ x = self.get_x_pred(x, noise_pred_prime, t_1, t_prev)
611
+ x = self.ad(x)
612
+ return x
diffusion/dpm_solver_pytorch.py ADDED
@@ -0,0 +1,1201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+
3
+ import torch
4
+
5
+
6
+ class NoiseScheduleVP:
7
+ def __init__(
8
+ self,
9
+ schedule='discrete',
10
+ betas=None,
11
+ alphas_cumprod=None,
12
+ continuous_beta_0=0.1,
13
+ continuous_beta_1=20.,
14
+ ):
15
+ """Create a wrapper class for the forward SDE (VP type).
16
+
17
+ ***
18
+ Update: We support discrete-time diffusion models by implementing a picewise linear interpolation for log_alpha_t.
19
+ We recommend to use schedule='discrete' for the discrete-time diffusion models, especially for high-resolution images.
20
+ ***
21
+
22
+ The forward SDE ensures that the condition distribution q_{t|0}(x_t | x_0) = N ( alpha_t * x_0, sigma_t^2 * I ).
23
+ We further define lambda_t = log(alpha_t) - log(sigma_t), which is the half-logSNR (described in the DPM-Solver paper).
24
+ Therefore, we implement the functions for computing alpha_t, sigma_t and lambda_t. For t in [0, T], we have:
25
+
26
+ log_alpha_t = self.marginal_log_mean_coeff(t)
27
+ sigma_t = self.marginal_std(t)
28
+ lambda_t = self.marginal_lambda(t)
29
+
30
+ Moreover, as lambda(t) is an invertible function, we also support its inverse function:
31
+
32
+ t = self.inverse_lambda(lambda_t)
33
+
34
+ ===============================================================
35
+
36
+ We support both discrete-time DPMs (trained on n = 0, 1, ..., N-1) and continuous-time DPMs (trained on t in [t_0, T]).
37
+
38
+ 1. For discrete-time DPMs:
39
+
40
+ For discrete-time DPMs trained on n = 0, 1, ..., N-1, we convert the discrete steps to continuous time steps by:
41
+ t_i = (i + 1) / N
42
+ e.g. for N = 1000, we have t_0 = 1e-3 and T = t_{N-1} = 1.
43
+ We solve the corresponding diffusion ODE from time T = 1 to time t_0 = 1e-3.
44
+
45
+ Args:
46
+ betas: A `torch.Tensor`. The beta array for the discrete-time DPM. (See the original DDPM paper for details)
47
+ alphas_cumprod: A `torch.Tensor`. The cumprod alphas for the discrete-time DPM. (See the original DDPM paper for details)
48
+
49
+ Note that we always have alphas_cumprod = cumprod(betas). Therefore, we only need to set one of `betas` and `alphas_cumprod`.
50
+
51
+ **Important**: Please pay special attention for the args for `alphas_cumprod`:
52
+ The `alphas_cumprod` is the \hat{alpha_n} arrays in the notations of DDPM. Specifically, DDPMs assume that
53
+ q_{t_n | 0}(x_{t_n} | x_0) = N ( \sqrt{\hat{alpha_n}} * x_0, (1 - \hat{alpha_n}) * I ).
54
+ Therefore, the notation \hat{alpha_n} is different from the notation alpha_t in DPM-Solver. In fact, we have
55
+ alpha_{t_n} = \sqrt{\hat{alpha_n}},
56
+ and
57
+ log(alpha_{t_n}) = 0.5 * log(\hat{alpha_n}).
58
+
59
+
60
+ 2. For continuous-time DPMs:
61
+
62
+ We support two types of VPSDEs: linear (DDPM) and cosine (improved-DDPM). The hyperparameters for the noise
63
+ schedule are the default settings in DDPM and improved-DDPM:
64
+
65
+ Args:
66
+ beta_min: A `float` number. The smallest beta for the linear schedule.
67
+ beta_max: A `float` number. The largest beta for the linear schedule.
68
+ cosine_s: A `float` number. The hyperparameter in the cosine schedule.
69
+ cosine_beta_max: A `float` number. The hyperparameter in the cosine schedule.
70
+ T: A `float` number. The ending time of the forward process.
71
+
72
+ ===============================================================
73
+
74
+ Args:
75
+ schedule: A `str`. The noise schedule of the forward SDE. 'discrete' for discrete-time DPMs,
76
+ 'linear' or 'cosine' for continuous-time DPMs.
77
+ Returns:
78
+ A wrapper object of the forward SDE (VP type).
79
+
80
+ ===============================================================
81
+
82
+ Example:
83
+
84
+ # For discrete-time DPMs, given betas (the beta array for n = 0, 1, ..., N - 1):
85
+ >>> ns = NoiseScheduleVP('discrete', betas=betas)
86
+
87
+ # For discrete-time DPMs, given alphas_cumprod (the \hat{alpha_n} array for n = 0, 1, ..., N - 1):
88
+ >>> ns = NoiseScheduleVP('discrete', alphas_cumprod=alphas_cumprod)
89
+
90
+ # For continuous-time DPMs (VPSDE), linear schedule:
91
+ >>> ns = NoiseScheduleVP('linear', continuous_beta_0=0.1, continuous_beta_1=20.)
92
+
93
+ """
94
+
95
+ if schedule not in ['discrete', 'linear', 'cosine']:
96
+ raise ValueError(
97
+ "Unsupported noise schedule {}. The schedule needs to be 'discrete' or 'linear' or 'cosine'".format(
98
+ schedule))
99
+
100
+ self.schedule = schedule
101
+ if schedule == 'discrete':
102
+ if betas is not None:
103
+ log_alphas = 0.5 * torch.log(1 - betas).cumsum(dim=0)
104
+ else:
105
+ assert alphas_cumprod is not None
106
+ log_alphas = 0.5 * torch.log(alphas_cumprod)
107
+ self.total_N = len(log_alphas)
108
+ self.T = 1.
109
+ self.t_array = torch.linspace(0., 1., self.total_N + 1)[1:].reshape((1, -1))
110
+ self.log_alpha_array = log_alphas.reshape((1, -1,))
111
+ else:
112
+ self.total_N = 1000
113
+ self.beta_0 = continuous_beta_0
114
+ self.beta_1 = continuous_beta_1
115
+ self.cosine_s = 0.008
116
+ self.cosine_beta_max = 999.
117
+ self.cosine_t_max = math.atan(self.cosine_beta_max * (1. + self.cosine_s) / math.pi) * 2. * (
118
+ 1. + self.cosine_s) / math.pi - self.cosine_s
119
+ self.cosine_log_alpha_0 = math.log(math.cos(self.cosine_s / (1. + self.cosine_s) * math.pi / 2.))
120
+ self.schedule = schedule
121
+ if schedule == 'cosine':
122
+ # For the cosine schedule, T = 1 will have numerical issues. So we manually set the ending time T.
123
+ # Note that T = 0.9946 may be not the optimal setting. However, we find it works well.
124
+ self.T = 0.9946
125
+ else:
126
+ self.T = 1.
127
+
128
+ def marginal_log_mean_coeff(self, t):
129
+ """
130
+ Compute log(alpha_t) of a given continuous-time label t in [0, T].
131
+ """
132
+ if self.schedule == 'discrete':
133
+ return interpolate_fn(t.reshape((-1, 1)), self.t_array.to(t.device),
134
+ self.log_alpha_array.to(t.device)).reshape((-1))
135
+ elif self.schedule == 'linear':
136
+ return -0.25 * t ** 2 * (self.beta_1 - self.beta_0) - 0.5 * t * self.beta_0
137
+ elif self.schedule == 'cosine':
138
+ log_alpha_fn = lambda s: torch.log(torch.cos((s + self.cosine_s) / (1. + self.cosine_s) * math.pi / 2.))
139
+ log_alpha_t = log_alpha_fn(t) - self.cosine_log_alpha_0
140
+ return log_alpha_t
141
+
142
+ def marginal_alpha(self, t):
143
+ """
144
+ Compute alpha_t of a given continuous-time label t in [0, T].
145
+ """
146
+ return torch.exp(self.marginal_log_mean_coeff(t))
147
+
148
+ def marginal_std(self, t):
149
+ """
150
+ Compute sigma_t of a given continuous-time label t in [0, T].
151
+ """
152
+ return torch.sqrt(1. - torch.exp(2. * self.marginal_log_mean_coeff(t)))
153
+
154
+ def marginal_lambda(self, t):
155
+ """
156
+ Compute lambda_t = log(alpha_t) - log(sigma_t) of a given continuous-time label t in [0, T].
157
+ """
158
+ log_mean_coeff = self.marginal_log_mean_coeff(t)
159
+ log_std = 0.5 * torch.log(1. - torch.exp(2. * log_mean_coeff))
160
+ return log_mean_coeff - log_std
161
+
162
+ def inverse_lambda(self, lamb):
163
+ """
164
+ Compute the continuous-time label t in [0, T] of a given half-logSNR lambda_t.
165
+ """
166
+ if self.schedule == 'linear':
167
+ tmp = 2. * (self.beta_1 - self.beta_0) * torch.logaddexp(-2. * lamb, torch.zeros((1,)).to(lamb))
168
+ Delta = self.beta_0 ** 2 + tmp
169
+ return tmp / (torch.sqrt(Delta) + self.beta_0) / (self.beta_1 - self.beta_0)
170
+ elif self.schedule == 'discrete':
171
+ log_alpha = -0.5 * torch.logaddexp(torch.zeros((1,)).to(lamb.device), -2. * lamb)
172
+ t = interpolate_fn(log_alpha.reshape((-1, 1)), torch.flip(self.log_alpha_array.to(lamb.device), [1]),
173
+ torch.flip(self.t_array.to(lamb.device), [1]))
174
+ return t.reshape((-1,))
175
+ else:
176
+ log_alpha = -0.5 * torch.logaddexp(-2. * lamb, torch.zeros((1,)).to(lamb))
177
+ t_fn = lambda log_alpha_t: torch.arccos(torch.exp(log_alpha_t + self.cosine_log_alpha_0)) * 2. * (
178
+ 1. + self.cosine_s) / math.pi - self.cosine_s
179
+ t = t_fn(log_alpha)
180
+ return t
181
+
182
+
183
+ def model_wrapper(
184
+ model,
185
+ noise_schedule,
186
+ model_type="noise",
187
+ model_kwargs={},
188
+ guidance_type="uncond",
189
+ condition=None,
190
+ unconditional_condition=None,
191
+ guidance_scale=1.,
192
+ classifier_fn=None,
193
+ classifier_kwargs={},
194
+ ):
195
+ """Create a wrapper function for the noise prediction model.
196
+
197
+ DPM-Solver needs to solve the continuous-time diffusion ODEs. For DPMs trained on discrete-time labels, we need to
198
+ firstly wrap the model function to a noise prediction model that accepts the continuous time as the input.
199
+
200
+ We support four types of the diffusion model by setting `model_type`:
201
+
202
+ 1. "noise": noise prediction model. (Trained by predicting noise).
203
+
204
+ 2. "x_start": data prediction model. (Trained by predicting the data x_0 at time 0).
205
+
206
+ 3. "v": velocity prediction model. (Trained by predicting the velocity).
207
+ The "v" prediction is derivation detailed in Appendix D of [1], and is used in Imagen-Video [2].
208
+
209
+ [1] Salimans, Tim, and Jonathan Ho. "Progressive distillation for fast sampling of diffusion models."
210
+ arXiv preprint arXiv:2202.00512 (2022).
211
+ [2] Ho, Jonathan, et al. "Imagen Video: High Definition Video Generation with Diffusion Models."
212
+ arXiv preprint arXiv:2210.02303 (2022).
213
+
214
+ 4. "score": marginal score function. (Trained by denoising score matching).
215
+ Note that the score function and the noise prediction model follows a simple relationship:
216
+ ```
217
+ noise(x_t, t) = -sigma_t * score(x_t, t)
218
+ ```
219
+
220
+ We support three types of guided sampling by DPMs by setting `guidance_type`:
221
+ 1. "uncond": unconditional sampling by DPMs.
222
+ The input `model` has the following format:
223
+ ``
224
+ model(x, t_input, **model_kwargs) -> noise | x_start | v | score
225
+ ``
226
+
227
+ 2. "classifier": classifier guidance sampling [3] by DPMs and another classifier.
228
+ The input `model` has the following format:
229
+ ``
230
+ model(x, t_input, **model_kwargs) -> noise | x_start | v | score
231
+ ``
232
+
233
+ The input `classifier_fn` has the following format:
234
+ ``
235
+ classifier_fn(x, t_input, cond, **classifier_kwargs) -> logits(x, t_input, cond)
236
+ ``
237
+
238
+ [3] P. Dhariwal and A. Q. Nichol, "Diffusion models beat GANs on image synthesis,"
239
+ in Advances in Neural Information Processing Systems, vol. 34, 2021, pp. 8780-8794.
240
+
241
+ 3. "classifier-free": classifier-free guidance sampling by conditional DPMs.
242
+ The input `model` has the following format:
243
+ ``
244
+ model(x, t_input, cond, **model_kwargs) -> noise | x_start | v | score
245
+ ``
246
+ And if cond == `unconditional_condition`, the model output is the unconditional DPM output.
247
+
248
+ [4] Ho, Jonathan, and Tim Salimans. "Classifier-free diffusion guidance."
249
+ arXiv preprint arXiv:2207.12598 (2022).
250
+
251
+
252
+ The `t_input` is the time label of the model, which may be discrete-time labels (i.e. 0 to 999)
253
+ or continuous-time labels (i.e. epsilon to T).
254
+
255
+ We wrap the model function to accept only `x` and `t_continuous` as inputs, and outputs the predicted noise:
256
+ ``
257
+ def model_fn(x, t_continuous) -> noise:
258
+ t_input = get_model_input_time(t_continuous)
259
+ return noise_pred(model, x, t_input, **model_kwargs)
260
+ ``
261
+ where `t_continuous` is the continuous time labels (i.e. epsilon to T). And we use `model_fn` for DPM-Solver.
262
+
263
+ ===============================================================
264
+
265
+ Args:
266
+ model: A diffusion model with the corresponding format described above.
267
+ noise_schedule: A noise schedule object, such as NoiseScheduleVP.
268
+ model_type: A `str`. The parameterization type of the diffusion model.
269
+ "noise" or "x_start" or "v" or "score".
270
+ model_kwargs: A `dict`. A dict for the other inputs of the model function.
271
+ guidance_type: A `str`. The type of the guidance for sampling.
272
+ "uncond" or "classifier" or "classifier-free".
273
+ condition: A pytorch tensor. The condition for the guided sampling.
274
+ Only used for "classifier" or "classifier-free" guidance type.
275
+ unconditional_condition: A pytorch tensor. The condition for the unconditional sampling.
276
+ Only used for "classifier-free" guidance type.
277
+ guidance_scale: A `float`. The scale for the guided sampling.
278
+ classifier_fn: A classifier function. Only used for the classifier guidance.
279
+ classifier_kwargs: A `dict`. A dict for the other inputs of the classifier function.
280
+ Returns:
281
+ A noise prediction model that accepts the noised data and the continuous time as the inputs.
282
+ """
283
+
284
+ def get_model_input_time(t_continuous):
285
+ """
286
+ Convert the continuous-time `t_continuous` (in [epsilon, T]) to the model input time.
287
+ For discrete-time DPMs, we convert `t_continuous` in [1 / N, 1] to `t_input` in [0, 1000 * (N - 1) / N].
288
+ For continuous-time DPMs, we just use `t_continuous`.
289
+ """
290
+ if noise_schedule.schedule == 'discrete':
291
+ return (t_continuous - 1. / noise_schedule.total_N) * noise_schedule.total_N
292
+ else:
293
+ return t_continuous
294
+
295
+ def noise_pred_fn(x, t_continuous, cond=None):
296
+ if t_continuous.reshape((-1,)).shape[0] == 1:
297
+ t_continuous = t_continuous.expand((x.shape[0]))
298
+ t_input = get_model_input_time(t_continuous)
299
+ if cond is None:
300
+ output = model(x, t_input, **model_kwargs)
301
+ else:
302
+ output = model(x, t_input, cond, **model_kwargs)
303
+ if model_type == "noise":
304
+ return output
305
+ elif model_type == "x_start":
306
+ alpha_t, sigma_t = noise_schedule.marginal_alpha(t_continuous), noise_schedule.marginal_std(t_continuous)
307
+ dims = x.dim()
308
+ return (x - expand_dims(alpha_t, dims) * output) / expand_dims(sigma_t, dims)
309
+ elif model_type == "v":
310
+ alpha_t, sigma_t = noise_schedule.marginal_alpha(t_continuous), noise_schedule.marginal_std(t_continuous)
311
+ dims = x.dim()
312
+ return expand_dims(alpha_t, dims) * output + expand_dims(sigma_t, dims) * x
313
+ elif model_type == "score":
314
+ sigma_t = noise_schedule.marginal_std(t_continuous)
315
+ dims = x.dim()
316
+ return -expand_dims(sigma_t, dims) * output
317
+
318
+ def cond_grad_fn(x, t_input):
319
+ """
320
+ Compute the gradient of the classifier, i.e. nabla_{x} log p_t(cond | x_t).
321
+ """
322
+ with torch.enable_grad():
323
+ x_in = x.detach().requires_grad_(True)
324
+ log_prob = classifier_fn(x_in, t_input, condition, **classifier_kwargs)
325
+ return torch.autograd.grad(log_prob.sum(), x_in)[0]
326
+
327
+ def model_fn(x, t_continuous):
328
+ """
329
+ The noise predicition model function that is used for DPM-Solver.
330
+ """
331
+ if t_continuous.reshape((-1,)).shape[0] == 1:
332
+ t_continuous = t_continuous.expand((x.shape[0]))
333
+ if guidance_type == "uncond":
334
+ return noise_pred_fn(x, t_continuous)
335
+ elif guidance_type == "classifier":
336
+ assert classifier_fn is not None
337
+ t_input = get_model_input_time(t_continuous)
338
+ cond_grad = cond_grad_fn(x, t_input)
339
+ sigma_t = noise_schedule.marginal_std(t_continuous)
340
+ noise = noise_pred_fn(x, t_continuous)
341
+ return noise - guidance_scale * expand_dims(sigma_t, dims=cond_grad.dim()) * cond_grad
342
+ elif guidance_type == "classifier-free":
343
+ if guidance_scale == 1. or unconditional_condition is None:
344
+ return noise_pred_fn(x, t_continuous, cond=condition)
345
+ else:
346
+ x_in = torch.cat([x] * 2)
347
+ t_in = torch.cat([t_continuous] * 2)
348
+ c_in = torch.cat([unconditional_condition, condition])
349
+ noise_uncond, noise = noise_pred_fn(x_in, t_in, cond=c_in).chunk(2)
350
+ return noise_uncond + guidance_scale * (noise - noise_uncond)
351
+
352
+ assert model_type in ["noise", "x_start", "v"]
353
+ assert guidance_type in ["uncond", "classifier", "classifier-free"]
354
+ return model_fn
355
+
356
+
357
+ class DPM_Solver:
358
+ def __init__(self, model_fn, noise_schedule, predict_x0=False, thresholding=False, max_val=1.):
359
+ """Construct a DPM-Solver.
360
+
361
+ We support both the noise prediction model ("predicting epsilon") and the data prediction model ("predicting x0").
362
+ If `predict_x0` is False, we use the solver for the noise prediction model (DPM-Solver).
363
+ If `predict_x0` is True, we use the solver for the data prediction model (DPM-Solver++).
364
+ In such case, we further support the "dynamic thresholding" in [1] when `thresholding` is True.
365
+ The "dynamic thresholding" can greatly improve the sample quality for pixel-space DPMs with large guidance scales.
366
+
367
+ Args:
368
+ model_fn: A noise prediction model function which accepts the continuous-time input (t in [epsilon, T]):
369
+ ``
370
+ def model_fn(x, t_continuous):
371
+ return noise
372
+ ``
373
+ noise_schedule: A noise schedule object, such as NoiseScheduleVP.
374
+ predict_x0: A `bool`. If true, use the data prediction model; else, use the noise prediction model.
375
+ thresholding: A `bool`. Valid when `predict_x0` is True. Whether to use the "dynamic thresholding" in [1].
376
+ max_val: A `float`. Valid when both `predict_x0` and `thresholding` are True. The max value for thresholding.
377
+
378
+ [1] Chitwan Saharia, William Chan, Saurabh Saxena, Lala Li, Jay Whang, Emily Denton, Seyed Kamyar Seyed Ghasemipour, Burcu Karagol Ayan, S Sara Mahdavi, Rapha Gontijo Lopes, et al. Photorealistic text-to-image diffusion models with deep language understanding. arXiv preprint arXiv:2205.11487, 2022b.
379
+ """
380
+ self.model = model_fn
381
+ self.noise_schedule = noise_schedule
382
+ self.predict_x0 = predict_x0
383
+ self.thresholding = thresholding
384
+ self.max_val = max_val
385
+
386
+ def noise_prediction_fn(self, x, t):
387
+ """
388
+ Return the noise prediction model.
389
+ """
390
+ return self.model(x, t)
391
+
392
+ def data_prediction_fn(self, x, t):
393
+ """
394
+ Return the data prediction model (with thresholding).
395
+ """
396
+ noise = self.noise_prediction_fn(x, t)
397
+ dims = x.dim()
398
+ alpha_t, sigma_t = self.noise_schedule.marginal_alpha(t), self.noise_schedule.marginal_std(t)
399
+ x0 = (x - expand_dims(sigma_t, dims) * noise) / expand_dims(alpha_t, dims)
400
+ if self.thresholding:
401
+ p = 0.995 # A hyperparameter in the paper of "Imagen" [1].
402
+ s = torch.quantile(torch.abs(x0).reshape((x0.shape[0], -1)), p, dim=1)
403
+ s = expand_dims(torch.maximum(s, self.max_val * torch.ones_like(s).to(s.device)), dims)
404
+ x0 = torch.clamp(x0, -s, s) / s
405
+ return x0
406
+
407
+ def model_fn(self, x, t):
408
+ """
409
+ Convert the model to the noise prediction model or the data prediction model.
410
+ """
411
+ if self.predict_x0:
412
+ return self.data_prediction_fn(x, t)
413
+ else:
414
+ return self.noise_prediction_fn(x, t)
415
+
416
+ def get_time_steps(self, skip_type, t_T, t_0, N, device):
417
+ """Compute the intermediate time steps for sampling.
418
+
419
+ Args:
420
+ skip_type: A `str`. The type for the spacing of the time steps. We support three types:
421
+ - 'logSNR': uniform logSNR for the time steps.
422
+ - 'time_uniform': uniform time for the time steps. (**Recommended for high-resolutional data**.)
423
+ - 'time_quadratic': quadratic time for the time steps. (Used in DDIM for low-resolutional data.)
424
+ t_T: A `float`. The starting time of the sampling (default is T).
425
+ t_0: A `float`. The ending time of the sampling (default is epsilon).
426
+ N: A `int`. The total number of the spacing of the time steps.
427
+ device: A torch device.
428
+ Returns:
429
+ A pytorch tensor of the time steps, with the shape (N + 1,).
430
+ """
431
+ if skip_type == 'logSNR':
432
+ lambda_T = self.noise_schedule.marginal_lambda(torch.tensor(t_T).to(device))
433
+ lambda_0 = self.noise_schedule.marginal_lambda(torch.tensor(t_0).to(device))
434
+ logSNR_steps = torch.linspace(lambda_T.cpu().item(), lambda_0.cpu().item(), N + 1).to(device)
435
+ return self.noise_schedule.inverse_lambda(logSNR_steps)
436
+ elif skip_type == 'time_uniform':
437
+ return torch.linspace(t_T, t_0, N + 1).to(device)
438
+ elif skip_type == 'time_quadratic':
439
+ t_order = 2
440
+ t = torch.linspace(t_T ** (1. / t_order), t_0 ** (1. / t_order), N + 1).pow(t_order).to(device)
441
+ return t
442
+ else:
443
+ raise ValueError(
444
+ "Unsupported skip_type {}, need to be 'logSNR' or 'time_uniform' or 'time_quadratic'".format(skip_type))
445
+
446
+ def get_orders_and_timesteps_for_singlestep_solver(self, steps, order, skip_type, t_T, t_0, device):
447
+ """
448
+ Get the order of each step for sampling by the singlestep DPM-Solver.
449
+
450
+ We combine both DPM-Solver-1,2,3 to use all the function evaluations, which is named as "DPM-Solver-fast".
451
+ Given a fixed number of function evaluations by `steps`, the sampling procedure by DPM-Solver-fast is:
452
+ - If order == 1:
453
+ We take `steps` of DPM-Solver-1 (i.e. DDIM).
454
+ - If order == 2:
455
+ - Denote K = (steps // 2). We take K or (K + 1) intermediate time steps for sampling.
456
+ - If steps % 2 == 0, we use K steps of DPM-Solver-2.
457
+ - If steps % 2 == 1, we use K steps of DPM-Solver-2 and 1 step of DPM-Solver-1.
458
+ - If order == 3:
459
+ - Denote K = (steps // 3 + 1). We take K intermediate time steps for sampling.
460
+ - If steps % 3 == 0, we use (K - 2) steps of DPM-Solver-3, and 1 step of DPM-Solver-2 and 1 step of DPM-Solver-1.
461
+ - If steps % 3 == 1, we use (K - 1) steps of DPM-Solver-3 and 1 step of DPM-Solver-1.
462
+ - If steps % 3 == 2, we use (K - 1) steps of DPM-Solver-3 and 1 step of DPM-Solver-2.
463
+
464
+ ============================================
465
+ Args:
466
+ order: A `int`. The max order for the solver (2 or 3).
467
+ steps: A `int`. The total number of function evaluations (NFE).
468
+ skip_type: A `str`. The type for the spacing of the time steps. We support three types:
469
+ - 'logSNR': uniform logSNR for the time steps.
470
+ - 'time_uniform': uniform time for the time steps. (**Recommended for high-resolutional data**.)
471
+ - 'time_quadratic': quadratic time for the time steps. (Used in DDIM for low-resolutional data.)
472
+ t_T: A `float`. The starting time of the sampling (default is T).
473
+ t_0: A `float`. The ending time of the sampling (default is epsilon).
474
+ device: A torch device.
475
+ Returns:
476
+ orders: A list of the solver order of each step.
477
+ """
478
+ if order == 3:
479
+ K = steps // 3 + 1
480
+ if steps % 3 == 0:
481
+ orders = [3, ] * (K - 2) + [2, 1]
482
+ elif steps % 3 == 1:
483
+ orders = [3, ] * (K - 1) + [1]
484
+ else:
485
+ orders = [3, ] * (K - 1) + [2]
486
+ elif order == 2:
487
+ if steps % 2 == 0:
488
+ K = steps // 2
489
+ orders = [2, ] * K
490
+ else:
491
+ K = steps // 2 + 1
492
+ orders = [2, ] * (K - 1) + [1]
493
+ elif order == 1:
494
+ K = 1
495
+ orders = [1, ] * steps
496
+ else:
497
+ raise ValueError("'order' must be '1' or '2' or '3'.")
498
+ if skip_type == 'logSNR':
499
+ # To reproduce the results in DPM-Solver paper
500
+ timesteps_outer = self.get_time_steps(skip_type, t_T, t_0, K, device)
501
+ else:
502
+ timesteps_outer = self.get_time_steps(skip_type, t_T, t_0, steps, device)[
503
+ torch.cumsum(torch.tensor([0, ] + orders), dim=0).to(device)]
504
+ return timesteps_outer, orders
505
+
506
+ def denoise_fn(self, x, s):
507
+ """
508
+ Denoise at the final step, which is equivalent to solve the ODE from lambda_s to infty by first-order discretization.
509
+ """
510
+ return self.data_prediction_fn(x, s)
511
+
512
+ def dpm_solver_first_update(self, x, s, t, model_s=None, return_intermediate=False):
513
+ """
514
+ DPM-Solver-1 (equivalent to DDIM) from time `s` to time `t`.
515
+
516
+ Args:
517
+ x: A pytorch tensor. The initial value at time `s`.
518
+ s: A pytorch tensor. The starting time, with the shape (x.shape[0],).
519
+ t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
520
+ model_s: A pytorch tensor. The model function evaluated at time `s`.
521
+ If `model_s` is None, we evaluate the model by `x` and `s`; otherwise we directly use it.
522
+ return_intermediate: A `bool`. If true, also return the model value at time `s`.
523
+ Returns:
524
+ x_t: A pytorch tensor. The approximated solution at time `t`.
525
+ """
526
+ ns = self.noise_schedule
527
+ dims = x.dim()
528
+ lambda_s, lambda_t = ns.marginal_lambda(s), ns.marginal_lambda(t)
529
+ h = lambda_t - lambda_s
530
+ log_alpha_s, log_alpha_t = ns.marginal_log_mean_coeff(s), ns.marginal_log_mean_coeff(t)
531
+ sigma_s, sigma_t = ns.marginal_std(s), ns.marginal_std(t)
532
+ alpha_t = torch.exp(log_alpha_t)
533
+
534
+ if self.predict_x0:
535
+ phi_1 = torch.expm1(-h)
536
+ if model_s is None:
537
+ model_s = self.model_fn(x, s)
538
+ x_t = (
539
+ expand_dims(sigma_t / sigma_s, dims) * x
540
+ - expand_dims(alpha_t * phi_1, dims) * model_s
541
+ )
542
+ if return_intermediate:
543
+ return x_t, {'model_s': model_s}
544
+ else:
545
+ return x_t
546
+ else:
547
+ phi_1 = torch.expm1(h)
548
+ if model_s is None:
549
+ model_s = self.model_fn(x, s)
550
+ x_t = (
551
+ expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x
552
+ - expand_dims(sigma_t * phi_1, dims) * model_s
553
+ )
554
+ if return_intermediate:
555
+ return x_t, {'model_s': model_s}
556
+ else:
557
+ return x_t
558
+
559
+ def singlestep_dpm_solver_second_update(self, x, s, t, r1=0.5, model_s=None, return_intermediate=False,
560
+ solver_type='dpm_solver'):
561
+ """
562
+ Singlestep solver DPM-Solver-2 from time `s` to time `t`.
563
+
564
+ Args:
565
+ x: A pytorch tensor. The initial value at time `s`.
566
+ s: A pytorch tensor. The starting time, with the shape (x.shape[0],).
567
+ t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
568
+ r1: A `float`. The hyperparameter of the second-order solver.
569
+ model_s: A pytorch tensor. The model function evaluated at time `s`.
570
+ If `model_s` is None, we evaluate the model by `x` and `s`; otherwise we directly use it.
571
+ return_intermediate: A `bool`. If true, also return the model value at time `s` and `s1` (the intermediate time).
572
+ solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
573
+ The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
574
+ Returns:
575
+ x_t: A pytorch tensor. The approximated solution at time `t`.
576
+ """
577
+ if solver_type not in ['dpm_solver', 'taylor']:
578
+ raise ValueError("'solver_type' must be either 'dpm_solver' or 'taylor', got {}".format(solver_type))
579
+ if r1 is None:
580
+ r1 = 0.5
581
+ ns = self.noise_schedule
582
+ dims = x.dim()
583
+ lambda_s, lambda_t = ns.marginal_lambda(s), ns.marginal_lambda(t)
584
+ h = lambda_t - lambda_s
585
+ lambda_s1 = lambda_s + r1 * h
586
+ s1 = ns.inverse_lambda(lambda_s1)
587
+ log_alpha_s, log_alpha_s1, log_alpha_t = ns.marginal_log_mean_coeff(s), ns.marginal_log_mean_coeff(
588
+ s1), ns.marginal_log_mean_coeff(t)
589
+ sigma_s, sigma_s1, sigma_t = ns.marginal_std(s), ns.marginal_std(s1), ns.marginal_std(t)
590
+ alpha_s1, alpha_t = torch.exp(log_alpha_s1), torch.exp(log_alpha_t)
591
+
592
+ if self.predict_x0:
593
+ phi_11 = torch.expm1(-r1 * h)
594
+ phi_1 = torch.expm1(-h)
595
+
596
+ if model_s is None:
597
+ model_s = self.model_fn(x, s)
598
+ x_s1 = (
599
+ expand_dims(sigma_s1 / sigma_s, dims) * x
600
+ - expand_dims(alpha_s1 * phi_11, dims) * model_s
601
+ )
602
+ model_s1 = self.model_fn(x_s1, s1)
603
+ if solver_type == 'dpm_solver':
604
+ x_t = (
605
+ expand_dims(sigma_t / sigma_s, dims) * x
606
+ - expand_dims(alpha_t * phi_1, dims) * model_s
607
+ - (0.5 / r1) * expand_dims(alpha_t * phi_1, dims) * (model_s1 - model_s)
608
+ )
609
+ elif solver_type == 'taylor':
610
+ x_t = (
611
+ expand_dims(sigma_t / sigma_s, dims) * x
612
+ - expand_dims(alpha_t * phi_1, dims) * model_s
613
+ + (1. / r1) * expand_dims(alpha_t * ((torch.exp(-h) - 1.) / h + 1.), dims) * (
614
+ model_s1 - model_s)
615
+ )
616
+ else:
617
+ phi_11 = torch.expm1(r1 * h)
618
+ phi_1 = torch.expm1(h)
619
+
620
+ if model_s is None:
621
+ model_s = self.model_fn(x, s)
622
+ x_s1 = (
623
+ expand_dims(torch.exp(log_alpha_s1 - log_alpha_s), dims) * x
624
+ - expand_dims(sigma_s1 * phi_11, dims) * model_s
625
+ )
626
+ model_s1 = self.model_fn(x_s1, s1)
627
+ if solver_type == 'dpm_solver':
628
+ x_t = (
629
+ expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x
630
+ - expand_dims(sigma_t * phi_1, dims) * model_s
631
+ - (0.5 / r1) * expand_dims(sigma_t * phi_1, dims) * (model_s1 - model_s)
632
+ )
633
+ elif solver_type == 'taylor':
634
+ x_t = (
635
+ expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x
636
+ - expand_dims(sigma_t * phi_1, dims) * model_s
637
+ - (1. / r1) * expand_dims(sigma_t * ((torch.exp(h) - 1.) / h - 1.), dims) * (model_s1 - model_s)
638
+ )
639
+ if return_intermediate:
640
+ return x_t, {'model_s': model_s, 'model_s1': model_s1}
641
+ else:
642
+ return x_t
643
+
644
+ def singlestep_dpm_solver_third_update(self, x, s, t, r1=1. / 3., r2=2. / 3., model_s=None, model_s1=None,
645
+ return_intermediate=False, solver_type='dpm_solver'):
646
+ """
647
+ Singlestep solver DPM-Solver-3 from time `s` to time `t`.
648
+
649
+ Args:
650
+ x: A pytorch tensor. The initial value at time `s`.
651
+ s: A pytorch tensor. The starting time, with the shape (x.shape[0],).
652
+ t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
653
+ r1: A `float`. The hyperparameter of the third-order solver.
654
+ r2: A `float`. The hyperparameter of the third-order solver.
655
+ model_s: A pytorch tensor. The model function evaluated at time `s`.
656
+ If `model_s` is None, we evaluate the model by `x` and `s`; otherwise we directly use it.
657
+ model_s1: A pytorch tensor. The model function evaluated at time `s1` (the intermediate time given by `r1`).
658
+ If `model_s1` is None, we evaluate the model at `s1`; otherwise we directly use it.
659
+ return_intermediate: A `bool`. If true, also return the model value at time `s`, `s1` and `s2` (the intermediate times).
660
+ solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
661
+ The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
662
+ Returns:
663
+ x_t: A pytorch tensor. The approximated solution at time `t`.
664
+ """
665
+ if solver_type not in ['dpm_solver', 'taylor']:
666
+ raise ValueError("'solver_type' must be either 'dpm_solver' or 'taylor', got {}".format(solver_type))
667
+ if r1 is None:
668
+ r1 = 1. / 3.
669
+ if r2 is None:
670
+ r2 = 2. / 3.
671
+ ns = self.noise_schedule
672
+ dims = x.dim()
673
+ lambda_s, lambda_t = ns.marginal_lambda(s), ns.marginal_lambda(t)
674
+ h = lambda_t - lambda_s
675
+ lambda_s1 = lambda_s + r1 * h
676
+ lambda_s2 = lambda_s + r2 * h
677
+ s1 = ns.inverse_lambda(lambda_s1)
678
+ s2 = ns.inverse_lambda(lambda_s2)
679
+ log_alpha_s, log_alpha_s1, log_alpha_s2, log_alpha_t = ns.marginal_log_mean_coeff(
680
+ s), ns.marginal_log_mean_coeff(s1), ns.marginal_log_mean_coeff(s2), ns.marginal_log_mean_coeff(t)
681
+ sigma_s, sigma_s1, sigma_s2, sigma_t = ns.marginal_std(s), ns.marginal_std(s1), ns.marginal_std(
682
+ s2), ns.marginal_std(t)
683
+ alpha_s1, alpha_s2, alpha_t = torch.exp(log_alpha_s1), torch.exp(log_alpha_s2), torch.exp(log_alpha_t)
684
+
685
+ if self.predict_x0:
686
+ phi_11 = torch.expm1(-r1 * h)
687
+ phi_12 = torch.expm1(-r2 * h)
688
+ phi_1 = torch.expm1(-h)
689
+ phi_22 = torch.expm1(-r2 * h) / (r2 * h) + 1.
690
+ phi_2 = phi_1 / h + 1.
691
+ phi_3 = phi_2 / h - 0.5
692
+
693
+ if model_s is None:
694
+ model_s = self.model_fn(x, s)
695
+ if model_s1 is None:
696
+ x_s1 = (
697
+ expand_dims(sigma_s1 / sigma_s, dims) * x
698
+ - expand_dims(alpha_s1 * phi_11, dims) * model_s
699
+ )
700
+ model_s1 = self.model_fn(x_s1, s1)
701
+ x_s2 = (
702
+ expand_dims(sigma_s2 / sigma_s, dims) * x
703
+ - expand_dims(alpha_s2 * phi_12, dims) * model_s
704
+ + r2 / r1 * expand_dims(alpha_s2 * phi_22, dims) * (model_s1 - model_s)
705
+ )
706
+ model_s2 = self.model_fn(x_s2, s2)
707
+ if solver_type == 'dpm_solver':
708
+ x_t = (
709
+ expand_dims(sigma_t / sigma_s, dims) * x
710
+ - expand_dims(alpha_t * phi_1, dims) * model_s
711
+ + (1. / r2) * expand_dims(alpha_t * phi_2, dims) * (model_s2 - model_s)
712
+ )
713
+ elif solver_type == 'taylor':
714
+ D1_0 = (1. / r1) * (model_s1 - model_s)
715
+ D1_1 = (1. / r2) * (model_s2 - model_s)
716
+ D1 = (r2 * D1_0 - r1 * D1_1) / (r2 - r1)
717
+ D2 = 2. * (D1_1 - D1_0) / (r2 - r1)
718
+ x_t = (
719
+ expand_dims(sigma_t / sigma_s, dims) * x
720
+ - expand_dims(alpha_t * phi_1, dims) * model_s
721
+ + expand_dims(alpha_t * phi_2, dims) * D1
722
+ - expand_dims(alpha_t * phi_3, dims) * D2
723
+ )
724
+ else:
725
+ phi_11 = torch.expm1(r1 * h)
726
+ phi_12 = torch.expm1(r2 * h)
727
+ phi_1 = torch.expm1(h)
728
+ phi_22 = torch.expm1(r2 * h) / (r2 * h) - 1.
729
+ phi_2 = phi_1 / h - 1.
730
+ phi_3 = phi_2 / h - 0.5
731
+
732
+ if model_s is None:
733
+ model_s = self.model_fn(x, s)
734
+ if model_s1 is None:
735
+ x_s1 = (
736
+ expand_dims(torch.exp(log_alpha_s1 - log_alpha_s), dims) * x
737
+ - expand_dims(sigma_s1 * phi_11, dims) * model_s
738
+ )
739
+ model_s1 = self.model_fn(x_s1, s1)
740
+ x_s2 = (
741
+ expand_dims(torch.exp(log_alpha_s2 - log_alpha_s), dims) * x
742
+ - expand_dims(sigma_s2 * phi_12, dims) * model_s
743
+ - r2 / r1 * expand_dims(sigma_s2 * phi_22, dims) * (model_s1 - model_s)
744
+ )
745
+ model_s2 = self.model_fn(x_s2, s2)
746
+ if solver_type == 'dpm_solver':
747
+ x_t = (
748
+ expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x
749
+ - expand_dims(sigma_t * phi_1, dims) * model_s
750
+ - (1. / r2) * expand_dims(sigma_t * phi_2, dims) * (model_s2 - model_s)
751
+ )
752
+ elif solver_type == 'taylor':
753
+ D1_0 = (1. / r1) * (model_s1 - model_s)
754
+ D1_1 = (1. / r2) * (model_s2 - model_s)
755
+ D1 = (r2 * D1_0 - r1 * D1_1) / (r2 - r1)
756
+ D2 = 2. * (D1_1 - D1_0) / (r2 - r1)
757
+ x_t = (
758
+ expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x
759
+ - expand_dims(sigma_t * phi_1, dims) * model_s
760
+ - expand_dims(sigma_t * phi_2, dims) * D1
761
+ - expand_dims(sigma_t * phi_3, dims) * D2
762
+ )
763
+
764
+ if return_intermediate:
765
+ return x_t, {'model_s': model_s, 'model_s1': model_s1, 'model_s2': model_s2}
766
+ else:
767
+ return x_t
768
+
769
+ def multistep_dpm_solver_second_update(self, x, model_prev_list, t_prev_list, t, solver_type="dpm_solver"):
770
+ """
771
+ Multistep solver DPM-Solver-2 from time `t_prev_list[-1]` to time `t`.
772
+
773
+ Args:
774
+ x: A pytorch tensor. The initial value at time `s`.
775
+ model_prev_list: A list of pytorch tensor. The previous computed model values.
776
+ t_prev_list: A list of pytorch tensor. The previous times, each time has the shape (x.shape[0],)
777
+ t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
778
+ solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
779
+ The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
780
+ Returns:
781
+ x_t: A pytorch tensor. The approximated solution at time `t`.
782
+ """
783
+ if solver_type not in ['dpm_solver', 'taylor']:
784
+ raise ValueError("'solver_type' must be either 'dpm_solver' or 'taylor', got {}".format(solver_type))
785
+ ns = self.noise_schedule
786
+ dims = x.dim()
787
+ model_prev_1, model_prev_0 = model_prev_list
788
+ t_prev_1, t_prev_0 = t_prev_list
789
+ lambda_prev_1, lambda_prev_0, lambda_t = ns.marginal_lambda(t_prev_1), ns.marginal_lambda(
790
+ t_prev_0), ns.marginal_lambda(t)
791
+ log_alpha_prev_0, log_alpha_t = ns.marginal_log_mean_coeff(t_prev_0), ns.marginal_log_mean_coeff(t)
792
+ sigma_prev_0, sigma_t = ns.marginal_std(t_prev_0), ns.marginal_std(t)
793
+ alpha_t = torch.exp(log_alpha_t)
794
+
795
+ h_0 = lambda_prev_0 - lambda_prev_1
796
+ h = lambda_t - lambda_prev_0
797
+ r0 = h_0 / h
798
+ D1_0 = expand_dims(1. / r0, dims) * (model_prev_0 - model_prev_1)
799
+ if self.predict_x0:
800
+ if solver_type == 'dpm_solver':
801
+ x_t = (
802
+ expand_dims(sigma_t / sigma_prev_0, dims) * x
803
+ - expand_dims(alpha_t * (torch.exp(-h) - 1.), dims) * model_prev_0
804
+ - 0.5 * expand_dims(alpha_t * (torch.exp(-h) - 1.), dims) * D1_0
805
+ )
806
+ elif solver_type == 'taylor':
807
+ x_t = (
808
+ expand_dims(sigma_t / sigma_prev_0, dims) * x
809
+ - expand_dims(alpha_t * (torch.exp(-h) - 1.), dims) * model_prev_0
810
+ + expand_dims(alpha_t * ((torch.exp(-h) - 1.) / h + 1.), dims) * D1_0
811
+ )
812
+ else:
813
+ if solver_type == 'dpm_solver':
814
+ x_t = (
815
+ expand_dims(torch.exp(log_alpha_t - log_alpha_prev_0), dims) * x
816
+ - expand_dims(sigma_t * (torch.exp(h) - 1.), dims) * model_prev_0
817
+ - 0.5 * expand_dims(sigma_t * (torch.exp(h) - 1.), dims) * D1_0
818
+ )
819
+ elif solver_type == 'taylor':
820
+ x_t = (
821
+ expand_dims(torch.exp(log_alpha_t - log_alpha_prev_0), dims) * x
822
+ - expand_dims(sigma_t * (torch.exp(h) - 1.), dims) * model_prev_0
823
+ - expand_dims(sigma_t * ((torch.exp(h) - 1.) / h - 1.), dims) * D1_0
824
+ )
825
+ return x_t
826
+
827
+ def multistep_dpm_solver_third_update(self, x, model_prev_list, t_prev_list, t, solver_type='dpm_solver'):
828
+ """
829
+ Multistep solver DPM-Solver-3 from time `t_prev_list[-1]` to time `t`.
830
+
831
+ Args:
832
+ x: A pytorch tensor. The initial value at time `s`.
833
+ model_prev_list: A list of pytorch tensor. The previous computed model values.
834
+ t_prev_list: A list of pytorch tensor. The previous times, each time has the shape (x.shape[0],)
835
+ t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
836
+ solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
837
+ The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
838
+ Returns:
839
+ x_t: A pytorch tensor. The approximated solution at time `t`.
840
+ """
841
+ ns = self.noise_schedule
842
+ dims = x.dim()
843
+ model_prev_2, model_prev_1, model_prev_0 = model_prev_list
844
+ t_prev_2, t_prev_1, t_prev_0 = t_prev_list
845
+ lambda_prev_2, lambda_prev_1, lambda_prev_0, lambda_t = ns.marginal_lambda(t_prev_2), ns.marginal_lambda(
846
+ t_prev_1), ns.marginal_lambda(t_prev_0), ns.marginal_lambda(t)
847
+ log_alpha_prev_0, log_alpha_t = ns.marginal_log_mean_coeff(t_prev_0), ns.marginal_log_mean_coeff(t)
848
+ sigma_prev_0, sigma_t = ns.marginal_std(t_prev_0), ns.marginal_std(t)
849
+ alpha_t = torch.exp(log_alpha_t)
850
+
851
+ h_1 = lambda_prev_1 - lambda_prev_2
852
+ h_0 = lambda_prev_0 - lambda_prev_1
853
+ h = lambda_t - lambda_prev_0
854
+ r0, r1 = h_0 / h, h_1 / h
855
+ D1_0 = expand_dims(1. / r0, dims) * (model_prev_0 - model_prev_1)
856
+ D1_1 = expand_dims(1. / r1, dims) * (model_prev_1 - model_prev_2)
857
+ D1 = D1_0 + expand_dims(r0 / (r0 + r1), dims) * (D1_0 - D1_1)
858
+ D2 = expand_dims(1. / (r0 + r1), dims) * (D1_0 - D1_1)
859
+ if self.predict_x0:
860
+ x_t = (
861
+ expand_dims(sigma_t / sigma_prev_0, dims) * x
862
+ - expand_dims(alpha_t * (torch.exp(-h) - 1.), dims) * model_prev_0
863
+ + expand_dims(alpha_t * ((torch.exp(-h) - 1.) / h + 1.), dims) * D1
864
+ - expand_dims(alpha_t * ((torch.exp(-h) - 1. + h) / h ** 2 - 0.5), dims) * D2
865
+ )
866
+ else:
867
+ x_t = (
868
+ expand_dims(torch.exp(log_alpha_t - log_alpha_prev_0), dims) * x
869
+ - expand_dims(sigma_t * (torch.exp(h) - 1.), dims) * model_prev_0
870
+ - expand_dims(sigma_t * ((torch.exp(h) - 1.) / h - 1.), dims) * D1
871
+ - expand_dims(sigma_t * ((torch.exp(h) - 1. - h) / h ** 2 - 0.5), dims) * D2
872
+ )
873
+ return x_t
874
+
875
+ def singlestep_dpm_solver_update(self, x, s, t, order, return_intermediate=False, solver_type='dpm_solver', r1=None,
876
+ r2=None):
877
+ """
878
+ Singlestep DPM-Solver with the order `order` from time `s` to time `t`.
879
+
880
+ Args:
881
+ x: A pytorch tensor. The initial value at time `s`.
882
+ s: A pytorch tensor. The starting time, with the shape (x.shape[0],).
883
+ t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
884
+ order: A `int`. The order of DPM-Solver. We only support order == 1 or 2 or 3.
885
+ return_intermediate: A `bool`. If true, also return the model value at time `s`, `s1` and `s2` (the intermediate times).
886
+ solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
887
+ The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
888
+ r1: A `float`. The hyperparameter of the second-order or third-order solver.
889
+ r2: A `float`. The hyperparameter of the third-order solver.
890
+ Returns:
891
+ x_t: A pytorch tensor. The approximated solution at time `t`.
892
+ """
893
+ if order == 1:
894
+ return self.dpm_solver_first_update(x, s, t, return_intermediate=return_intermediate)
895
+ elif order == 2:
896
+ return self.singlestep_dpm_solver_second_update(x, s, t, return_intermediate=return_intermediate,
897
+ solver_type=solver_type, r1=r1)
898
+ elif order == 3:
899
+ return self.singlestep_dpm_solver_third_update(x, s, t, return_intermediate=return_intermediate,
900
+ solver_type=solver_type, r1=r1, r2=r2)
901
+ else:
902
+ raise ValueError("Solver order must be 1 or 2 or 3, got {}".format(order))
903
+
904
+ def multistep_dpm_solver_update(self, x, model_prev_list, t_prev_list, t, order, solver_type='dpm_solver'):
905
+ """
906
+ Multistep DPM-Solver with the order `order` from time `t_prev_list[-1]` to time `t`.
907
+
908
+ Args:
909
+ x: A pytorch tensor. The initial value at time `s`.
910
+ model_prev_list: A list of pytorch tensor. The previous computed model values.
911
+ t_prev_list: A list of pytorch tensor. The previous times, each time has the shape (x.shape[0],)
912
+ t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
913
+ order: A `int`. The order of DPM-Solver. We only support order == 1 or 2 or 3.
914
+ solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
915
+ The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
916
+ Returns:
917
+ x_t: A pytorch tensor. The approximated solution at time `t`.
918
+ """
919
+ if order == 1:
920
+ return self.dpm_solver_first_update(x, t_prev_list[-1], t, model_s=model_prev_list[-1])
921
+ elif order == 2:
922
+ return self.multistep_dpm_solver_second_update(x, model_prev_list, t_prev_list, t, solver_type=solver_type)
923
+ elif order == 3:
924
+ return self.multistep_dpm_solver_third_update(x, model_prev_list, t_prev_list, t, solver_type=solver_type)
925
+ else:
926
+ raise ValueError("Solver order must be 1 or 2 or 3, got {}".format(order))
927
+
928
+ def dpm_solver_adaptive(self, x, order, t_T, t_0, h_init=0.05, atol=0.0078, rtol=0.05, theta=0.9, t_err=1e-5,
929
+ solver_type='dpm_solver'):
930
+ """
931
+ The adaptive step size solver based on singlestep DPM-Solver.
932
+
933
+ Args:
934
+ x: A pytorch tensor. The initial value at time `t_T`.
935
+ order: A `int`. The (higher) order of the solver. We only support order == 2 or 3.
936
+ t_T: A `float`. The starting time of the sampling (default is T).
937
+ t_0: A `float`. The ending time of the sampling (default is epsilon).
938
+ h_init: A `float`. The initial step size (for logSNR).
939
+ atol: A `float`. The absolute tolerance of the solver. For image data, the default setting is 0.0078, followed [1].
940
+ rtol: A `float`. The relative tolerance of the solver. The default setting is 0.05.
941
+ theta: A `float`. The safety hyperparameter for adapting the step size. The default setting is 0.9, followed [1].
942
+ t_err: A `float`. The tolerance for the time. We solve the diffusion ODE until the absolute error between the
943
+ current time and `t_0` is less than `t_err`. The default setting is 1e-5.
944
+ solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
945
+ The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
946
+ Returns:
947
+ x_0: A pytorch tensor. The approximated solution at time `t_0`.
948
+
949
+ [1] A. Jolicoeur-Martineau, K. Li, R. Piché-Taillefer, T. Kachman, and I. Mitliagkas, "Gotta go fast when generating data with score-based models," arXiv preprint arXiv:2105.14080, 2021.
950
+ """
951
+ ns = self.noise_schedule
952
+ s = t_T * torch.ones((x.shape[0],)).to(x)
953
+ lambda_s = ns.marginal_lambda(s)
954
+ lambda_0 = ns.marginal_lambda(t_0 * torch.ones_like(s).to(x))
955
+ h = h_init * torch.ones_like(s).to(x)
956
+ x_prev = x
957
+ nfe = 0
958
+ if order == 2:
959
+ r1 = 0.5
960
+ lower_update = lambda x, s, t: self.dpm_solver_first_update(x, s, t, return_intermediate=True)
961
+ higher_update = lambda x, s, t, **kwargs: self.singlestep_dpm_solver_second_update(x, s, t, r1=r1,
962
+ solver_type=solver_type,
963
+ **kwargs)
964
+ elif order == 3:
965
+ r1, r2 = 1. / 3., 2. / 3.
966
+ lower_update = lambda x, s, t: self.singlestep_dpm_solver_second_update(x, s, t, r1=r1,
967
+ return_intermediate=True,
968
+ solver_type=solver_type)
969
+ higher_update = lambda x, s, t, **kwargs: self.singlestep_dpm_solver_third_update(x, s, t, r1=r1, r2=r2,
970
+ solver_type=solver_type,
971
+ **kwargs)
972
+ else:
973
+ raise ValueError("For adaptive step size solver, order must be 2 or 3, got {}".format(order))
974
+ while torch.abs((s - t_0)).mean() > t_err:
975
+ t = ns.inverse_lambda(lambda_s + h)
976
+ x_lower, lower_noise_kwargs = lower_update(x, s, t)
977
+ x_higher = higher_update(x, s, t, **lower_noise_kwargs)
978
+ delta = torch.max(torch.ones_like(x).to(x) * atol, rtol * torch.max(torch.abs(x_lower), torch.abs(x_prev)))
979
+ norm_fn = lambda v: torch.sqrt(torch.square(v.reshape((v.shape[0], -1))).mean(dim=-1, keepdim=True))
980
+ E = norm_fn((x_higher - x_lower) / delta).max()
981
+ if torch.all(E <= 1.):
982
+ x = x_higher
983
+ s = t
984
+ x_prev = x_lower
985
+ lambda_s = ns.marginal_lambda(s)
986
+ h = torch.min(theta * h * torch.float_power(E, -1. / order).float(), lambda_0 - lambda_s)
987
+ nfe += order
988
+ print('adaptive solver nfe', nfe)
989
+ return x
990
+
991
+ def sample(self, x, steps=20, t_start=None, t_end=None, order=3, skip_type='time_uniform',
992
+ method='singlestep', denoise=False, solver_type='dpm_solver', atol=0.0078,
993
+ rtol=0.05,
994
+ ):
995
+ """
996
+ Compute the sample at time `t_end` by DPM-Solver, given the initial `x` at time `t_start`.
997
+
998
+ =====================================================
999
+
1000
+ We support the following algorithms for both noise prediction model and data prediction model:
1001
+ - 'singlestep':
1002
+ Singlestep DPM-Solver (i.e. "DPM-Solver-fast" in the paper), which combines different orders of singlestep DPM-Solver.
1003
+ We combine all the singlestep solvers with order <= `order` to use up all the function evaluations (steps).
1004
+ The total number of function evaluations (NFE) == `steps`.
1005
+ Given a fixed NFE == `steps`, the sampling procedure is:
1006
+ - If `order` == 1:
1007
+ - Denote K = steps. We use K steps of DPM-Solver-1 (i.e. DDIM).
1008
+ - If `order` == 2:
1009
+ - Denote K = (steps // 2) + (steps % 2). We take K intermediate time steps for sampling.
1010
+ - If steps % 2 == 0, we use K steps of singlestep DPM-Solver-2.
1011
+ - If steps % 2 == 1, we use (K - 1) steps of singlestep DPM-Solver-2 and 1 step of DPM-Solver-1.
1012
+ - If `order` == 3:
1013
+ - Denote K = (steps // 3 + 1). We take K intermediate time steps for sampling.
1014
+ - If steps % 3 == 0, we use (K - 2) steps of singlestep DPM-Solver-3, and 1 step of singlestep DPM-Solver-2 and 1 step of DPM-Solver-1.
1015
+ - If steps % 3 == 1, we use (K - 1) steps of singlestep DPM-Solver-3 and 1 step of DPM-Solver-1.
1016
+ - If steps % 3 == 2, we use (K - 1) steps of singlestep DPM-Solver-3 and 1 step of singlestep DPM-Solver-2.
1017
+ - 'multistep':
1018
+ Multistep DPM-Solver with the order of `order`. The total number of function evaluations (NFE) == `steps`.
1019
+ We initialize the first `order` values by lower order multistep solvers.
1020
+ Given a fixed NFE == `steps`, the sampling procedure is:
1021
+ Denote K = steps.
1022
+ - If `order` == 1:
1023
+ - We use K steps of DPM-Solver-1 (i.e. DDIM).
1024
+ - If `order` == 2:
1025
+ - We firstly use 1 step of DPM-Solver-1, then use (K - 1) step of multistep DPM-Solver-2.
1026
+ - If `order` == 3:
1027
+ - We firstly use 1 step of DPM-Solver-1, then 1 step of multistep DPM-Solver-2, then (K - 2) step of multistep DPM-Solver-3.
1028
+ - 'singlestep_fixed':
1029
+ Fixed order singlestep DPM-Solver (i.e. DPM-Solver-1 or singlestep DPM-Solver-2 or singlestep DPM-Solver-3).
1030
+ We use singlestep DPM-Solver-`order` for `order`=1 or 2 or 3, with total [`steps` // `order`] * `order` NFE.
1031
+ - 'adaptive':
1032
+ Adaptive step size DPM-Solver (i.e. "DPM-Solver-12" and "DPM-Solver-23" in the paper).
1033
+ We ignore `steps` and use adaptive step size DPM-Solver with a higher order of `order`.
1034
+ You can adjust the absolute tolerance `atol` and the relative tolerance `rtol` to balance the computatation costs
1035
+ (NFE) and the sample quality.
1036
+ - If `order` == 2, we use DPM-Solver-12 which combines DPM-Solver-1 and singlestep DPM-Solver-2.
1037
+ - If `order` == 3, we use DPM-Solver-23 which combines singlestep DPM-Solver-2 and singlestep DPM-Solver-3.
1038
+
1039
+ =====================================================
1040
+
1041
+ Some advices for choosing the algorithm:
1042
+ - For **unconditional sampling** or **guided sampling with small guidance scale** by DPMs:
1043
+ Use singlestep DPM-Solver ("DPM-Solver-fast" in the paper) with `order = 3`.
1044
+ e.g.
1045
+ >>> dpm_solver = DPM_Solver(model_fn, noise_schedule, predict_x0=False)
1046
+ >>> x_sample = dpm_solver.sample(x, steps=steps, t_start=t_start, t_end=t_end, order=3,
1047
+ skip_type='time_uniform', method='singlestep')
1048
+ - For **guided sampling with large guidance scale** by DPMs:
1049
+ Use multistep DPM-Solver with `predict_x0 = True` and `order = 2`.
1050
+ e.g.
1051
+ >>> dpm_solver = DPM_Solver(model_fn, noise_schedule, predict_x0=True)
1052
+ >>> x_sample = dpm_solver.sample(x, steps=steps, t_start=t_start, t_end=t_end, order=2,
1053
+ skip_type='time_uniform', method='multistep')
1054
+
1055
+ We support three types of `skip_type`:
1056
+ - 'logSNR': uniform logSNR for the time steps. **Recommended for low-resolutional images**
1057
+ - 'time_uniform': uniform time for the time steps. **Recommended for high-resolutional images**.
1058
+ - 'time_quadratic': quadratic time for the time steps.
1059
+
1060
+ =====================================================
1061
+ Args:
1062
+ x: A pytorch tensor. The initial value at time `t_start`
1063
+ e.g. if `t_start` == T, then `x` is a sample from the standard normal distribution.
1064
+ steps: A `int`. The total number of function evaluations (NFE).
1065
+ t_start: A `float`. The starting time of the sampling.
1066
+ If `T` is None, we use self.noise_schedule.T (default is 1.0).
1067
+ t_end: A `float`. The ending time of the sampling.
1068
+ If `t_end` is None, we use 1. / self.noise_schedule.total_N.
1069
+ e.g. if total_N == 1000, we have `t_end` == 1e-3.
1070
+ For discrete-time DPMs:
1071
+ - We recommend `t_end` == 1. / self.noise_schedule.total_N.
1072
+ For continuous-time DPMs:
1073
+ - We recommend `t_end` == 1e-3 when `steps` <= 15; and `t_end` == 1e-4 when `steps` > 15.
1074
+ order: A `int`. The order of DPM-Solver.
1075
+ skip_type: A `str`. The type for the spacing of the time steps. 'time_uniform' or 'logSNR' or 'time_quadratic'.
1076
+ method: A `str`. The method for sampling. 'singlestep' or 'multistep' or 'singlestep_fixed' or 'adaptive'.
1077
+ denoise: A `bool`. Whether to denoise at the final step. Default is False.
1078
+ If `denoise` is True, the total NFE is (`steps` + 1).
1079
+ solver_type: A `str`. The taylor expansion type for the solver. `dpm_solver` or `taylor`. We recommend `dpm_solver`.
1080
+ atol: A `float`. The absolute tolerance of the adaptive step size solver. Valid when `method` == 'adaptive'.
1081
+ rtol: A `float`. The relative tolerance of the adaptive step size solver. Valid when `method` == 'adaptive'.
1082
+ Returns:
1083
+ x_end: A pytorch tensor. The approximated solution at time `t_end`.
1084
+
1085
+ """
1086
+ t_0 = 1. / self.noise_schedule.total_N if t_end is None else t_end
1087
+ t_T = self.noise_schedule.T if t_start is None else t_start
1088
+ device = x.device
1089
+ if method == 'adaptive':
1090
+ with torch.no_grad():
1091
+ x = self.dpm_solver_adaptive(x, order=order, t_T=t_T, t_0=t_0, atol=atol, rtol=rtol,
1092
+ solver_type=solver_type)
1093
+ elif method == 'multistep':
1094
+ assert steps >= order
1095
+ timesteps = self.get_time_steps(skip_type=skip_type, t_T=t_T, t_0=t_0, N=steps, device=device)
1096
+ assert timesteps.shape[0] - 1 == steps
1097
+ with torch.no_grad():
1098
+ vec_t = timesteps[0].expand((x.shape[0]))
1099
+ model_prev_list = [self.model_fn(x, vec_t)]
1100
+ t_prev_list = [vec_t]
1101
+ # Init the first `order` values by lower order multistep DPM-Solver.
1102
+ for init_order in range(1, order):
1103
+ vec_t = timesteps[init_order].expand(x.shape[0])
1104
+ x = self.multistep_dpm_solver_update(x, model_prev_list, t_prev_list, vec_t, init_order,
1105
+ solver_type=solver_type)
1106
+ model_prev_list.append(self.model_fn(x, vec_t))
1107
+ t_prev_list.append(vec_t)
1108
+ # Compute the remaining values by `order`-th order multistep DPM-Solver.
1109
+ for step in range(order, steps + 1):
1110
+ vec_t = timesteps[step].expand(x.shape[0])
1111
+ x = self.multistep_dpm_solver_update(x, model_prev_list, t_prev_list, vec_t, order,
1112
+ solver_type=solver_type)
1113
+ for i in range(order - 1):
1114
+ t_prev_list[i] = t_prev_list[i + 1]
1115
+ model_prev_list[i] = model_prev_list[i + 1]
1116
+ t_prev_list[-1] = vec_t
1117
+ # We do not need to evaluate the final model value.
1118
+ if step < steps:
1119
+ model_prev_list[-1] = self.model_fn(x, vec_t)
1120
+ elif method in ['singlestep', 'singlestep_fixed']:
1121
+ if method == 'singlestep':
1122
+ timesteps_outer, orders = self.get_orders_and_timesteps_for_singlestep_solver(steps=steps, order=order,
1123
+ skip_type=skip_type,
1124
+ t_T=t_T, t_0=t_0,
1125
+ device=device)
1126
+ elif method == 'singlestep_fixed':
1127
+ K = steps // order
1128
+ orders = [order, ] * K
1129
+ timesteps_outer = self.get_time_steps(skip_type=skip_type, t_T=t_T, t_0=t_0, N=K, device=device)
1130
+ for i, order in enumerate(orders):
1131
+ t_T_inner, t_0_inner = timesteps_outer[i], timesteps_outer[i + 1]
1132
+ timesteps_inner = self.get_time_steps(skip_type=skip_type, t_T=t_T_inner.item(), t_0=t_0_inner.item(),
1133
+ N=order, device=device)
1134
+ lambda_inner = self.noise_schedule.marginal_lambda(timesteps_inner)
1135
+ vec_s, vec_t = t_T_inner.repeat(x.shape[0]), t_0_inner.repeat(x.shape[0])
1136
+ h = lambda_inner[-1] - lambda_inner[0]
1137
+ r1 = None if order <= 1 else (lambda_inner[1] - lambda_inner[0]) / h
1138
+ r2 = None if order <= 2 else (lambda_inner[2] - lambda_inner[0]) / h
1139
+ x = self.singlestep_dpm_solver_update(x, vec_s, vec_t, order, solver_type=solver_type, r1=r1, r2=r2)
1140
+ if denoise:
1141
+ x = self.denoise_fn(x, torch.ones((x.shape[0],)).to(device) * t_0)
1142
+ return x
1143
+
1144
+
1145
+ #############################################################
1146
+ # other utility functions
1147
+ #############################################################
1148
+
1149
+ def interpolate_fn(x, xp, yp):
1150
+ """
1151
+ A piecewise linear function y = f(x), using xp and yp as keypoints.
1152
+ We implement f(x) in a differentiable way (i.e. applicable for autograd).
1153
+ The function f(x) is well-defined for all x-axis. (For x beyond the bounds of xp, we use the outmost points of xp to define the linear function.)
1154
+
1155
+ Args:
1156
+ x: PyTorch tensor with shape [N, C], where N is the batch size, C is the number of channels (we use C = 1 for DPM-Solver).
1157
+ xp: PyTorch tensor with shape [C, K], where K is the number of keypoints.
1158
+ yp: PyTorch tensor with shape [C, K].
1159
+ Returns:
1160
+ The function values f(x), with shape [N, C].
1161
+ """
1162
+ N, K = x.shape[0], xp.shape[1]
1163
+ all_x = torch.cat([x.unsqueeze(2), xp.unsqueeze(0).repeat((N, 1, 1))], dim=2)
1164
+ sorted_all_x, x_indices = torch.sort(all_x, dim=2)
1165
+ x_idx = torch.argmin(x_indices, dim=2)
1166
+ cand_start_idx = x_idx - 1
1167
+ start_idx = torch.where(
1168
+ torch.eq(x_idx, 0),
1169
+ torch.tensor(1, device=x.device),
1170
+ torch.where(
1171
+ torch.eq(x_idx, K), torch.tensor(K - 2, device=x.device), cand_start_idx,
1172
+ ),
1173
+ )
1174
+ end_idx = torch.where(torch.eq(start_idx, cand_start_idx), start_idx + 2, start_idx + 1)
1175
+ start_x = torch.gather(sorted_all_x, dim=2, index=start_idx.unsqueeze(2)).squeeze(2)
1176
+ end_x = torch.gather(sorted_all_x, dim=2, index=end_idx.unsqueeze(2)).squeeze(2)
1177
+ start_idx2 = torch.where(
1178
+ torch.eq(x_idx, 0),
1179
+ torch.tensor(0, device=x.device),
1180
+ torch.where(
1181
+ torch.eq(x_idx, K), torch.tensor(K - 2, device=x.device), cand_start_idx,
1182
+ ),
1183
+ )
1184
+ y_positions_expanded = yp.unsqueeze(0).expand(N, -1, -1)
1185
+ start_y = torch.gather(y_positions_expanded, dim=2, index=start_idx2.unsqueeze(2)).squeeze(2)
1186
+ end_y = torch.gather(y_positions_expanded, dim=2, index=(start_idx2 + 1).unsqueeze(2)).squeeze(2)
1187
+ cand = start_y + (x - start_x) * (end_y - start_y) / (end_x - start_x)
1188
+ return cand
1189
+
1190
+
1191
+ def expand_dims(v, dims):
1192
+ """
1193
+ Expand the tensor `v` to the dim `dims`.
1194
+
1195
+ Args:
1196
+ `v`: a PyTorch tensor with shape [N].
1197
+ `dim`: a `int`.
1198
+ Returns:
1199
+ a PyTorch tensor with shape [N, 1, 1, ..., 1] and the total dimension is `dims`.
1200
+ """
1201
+ return v[(...,) + (None,) * (dims - 1)]
diffusion/how to export onnx.md ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ - Open [onnx_export](onnx_export.py)
2
+ - project_name = "dddsp" change "project_name" to your project name
3
+ - model_path = f'{project_name}/model_500000.pt' change "model_path" to your model path
4
+ - Run
diffusion/infer_gt_mel.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ import torch.nn.functional as F
4
+ from diffusion.unit2mel import load_model_vocoder
5
+
6
+
7
+ class DiffGtMel:
8
+ def __init__(self, project_path=None, device=None):
9
+ self.project_path = project_path
10
+ if device is not None:
11
+ self.device = device
12
+ else:
13
+ self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
14
+ self.model = None
15
+ self.vocoder = None
16
+ self.args = None
17
+
18
+ def flush_model(self, project_path, ddsp_config=None):
19
+ if (self.model is None) or (project_path != self.project_path):
20
+ model, vocoder, args = load_model_vocoder(project_path, device=self.device)
21
+ if self.check_args(ddsp_config, args):
22
+ self.model = model
23
+ self.vocoder = vocoder
24
+ self.args = args
25
+
26
+ def check_args(self, args1, args2):
27
+ if args1.data.block_size != args2.data.block_size:
28
+ raise ValueError("DDSP与DIFF模型的block_size不一致")
29
+ if args1.data.sampling_rate != args2.data.sampling_rate:
30
+ raise ValueError("DDSP与DIFF模型的sampling_rate不一致")
31
+ if args1.data.encoder != args2.data.encoder:
32
+ raise ValueError("DDSP与DIFF模型的encoder不一致")
33
+ return True
34
+
35
+ def __call__(self, audio, f0, hubert, volume, acc=1, spk_id=1, k_step=0, method='pndm',
36
+ spk_mix_dict=None, start_frame=0):
37
+ input_mel = self.vocoder.extract(audio, self.args.data.sampling_rate)
38
+ out_mel = self.model(
39
+ hubert,
40
+ f0,
41
+ volume,
42
+ spk_id=spk_id,
43
+ spk_mix_dict=spk_mix_dict,
44
+ gt_spec=input_mel,
45
+ infer=True,
46
+ infer_speedup=acc,
47
+ method=method,
48
+ k_step=k_step,
49
+ use_tqdm=False)
50
+ if start_frame > 0:
51
+ out_mel = out_mel[:, start_frame:, :]
52
+ f0 = f0[:, start_frame:, :]
53
+ output = self.vocoder.infer(out_mel, f0)
54
+ if start_frame > 0:
55
+ output = F.pad(output, (start_frame * self.vocoder.vocoder_hop_size, 0))
56
+ return output
57
+
58
+ def infer(self, audio, f0, hubert, volume, acc=1, spk_id=1, k_step=0, method='pndm', silence_front=0,
59
+ use_silence=False, spk_mix_dict=None):
60
+ start_frame = int(silence_front * self.vocoder.vocoder_sample_rate / self.vocoder.vocoder_hop_size)
61
+ if use_silence:
62
+ audio = audio[:, start_frame * self.vocoder.vocoder_hop_size:]
63
+ f0 = f0[:, start_frame:, :]
64
+ hubert = hubert[:, start_frame:, :]
65
+ volume = volume[:, start_frame:, :]
66
+ _start_frame = 0
67
+ else:
68
+ _start_frame = start_frame
69
+ audio = self.__call__(audio, f0, hubert, volume, acc=acc, spk_id=spk_id, k_step=k_step,
70
+ method=method, spk_mix_dict=spk_mix_dict, start_frame=_start_frame)
71
+ if use_silence:
72
+ if start_frame > 0:
73
+ audio = F.pad(audio, (start_frame * self.vocoder.vocoder_hop_size, 0))
74
+ return audio
diffusion/logger/__init__.py ADDED
File without changes
diffusion/logger/__pycache__/__init__.cpython-38.pyc ADDED
Binary file (138 Bytes). View file
 
diffusion/logger/__pycache__/saver.cpython-38.pyc ADDED
Binary file (4 kB). View file
 
diffusion/logger/__pycache__/utils.cpython-38.pyc ADDED
Binary file (3.8 kB). View file
 
diffusion/logger/saver.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ author: wayn391@mastertones
3
+ '''
4
+
5
+ import os
6
+ import json
7
+ import time
8
+ import yaml
9
+ import datetime
10
+ import torch
11
+ import matplotlib.pyplot as plt
12
+ from . import utils
13
+ from torch.utils.tensorboard import SummaryWriter
14
+
15
+ class Saver(object):
16
+ def __init__(
17
+ self,
18
+ args,
19
+ initial_global_step=-1):
20
+
21
+ self.expdir = args.env.expdir
22
+ self.sample_rate = args.data.sampling_rate
23
+
24
+ # cold start
25
+ self.global_step = initial_global_step
26
+ self.init_time = time.time()
27
+ self.last_time = time.time()
28
+
29
+ # makedirs
30
+ os.makedirs(self.expdir, exist_ok=True)
31
+
32
+ # path
33
+ self.path_log_info = os.path.join(self.expdir, 'log_info.txt')
34
+
35
+ # ckpt
36
+ os.makedirs(self.expdir, exist_ok=True)
37
+
38
+ # writer
39
+ self.writer = SummaryWriter(os.path.join(self.expdir, 'logs'))
40
+
41
+ # save config
42
+ path_config = os.path.join(self.expdir, 'config.yaml')
43
+ with open(path_config, "w") as out_config:
44
+ yaml.dump(dict(args), out_config)
45
+
46
+
47
+ def log_info(self, msg):
48
+ '''log method'''
49
+ if isinstance(msg, dict):
50
+ msg_list = []
51
+ for k, v in msg.items():
52
+ tmp_str = ''
53
+ if isinstance(v, int):
54
+ tmp_str = '{}: {:,}'.format(k, v)
55
+ else:
56
+ tmp_str = '{}: {}'.format(k, v)
57
+
58
+ msg_list.append(tmp_str)
59
+ msg_str = '\n'.join(msg_list)
60
+ else:
61
+ msg_str = msg
62
+
63
+ # dsplay
64
+ print(msg_str)
65
+
66
+ # save
67
+ with open(self.path_log_info, 'a') as fp:
68
+ fp.write(msg_str+'\n')
69
+
70
+ def log_value(self, dict):
71
+ for k, v in dict.items():
72
+ self.writer.add_scalar(k, v, self.global_step)
73
+
74
+ def log_spec(self, name, spec, spec_out, vmin=-14, vmax=3.5):
75
+ spec_cat = torch.cat([(spec_out - spec).abs() + vmin, spec, spec_out], -1)
76
+ spec = spec_cat[0]
77
+ if isinstance(spec, torch.Tensor):
78
+ spec = spec.cpu().numpy()
79
+ fig = plt.figure(figsize=(12, 9))
80
+ plt.pcolor(spec.T, vmin=vmin, vmax=vmax)
81
+ plt.tight_layout()
82
+ self.writer.add_figure(name, fig, self.global_step)
83
+
84
+ def log_audio(self, dict):
85
+ for k, v in dict.items():
86
+ self.writer.add_audio(k, v, global_step=self.global_step, sample_rate=self.sample_rate)
87
+
88
+ def get_interval_time(self, update=True):
89
+ cur_time = time.time()
90
+ time_interval = cur_time - self.last_time
91
+ if update:
92
+ self.last_time = cur_time
93
+ return time_interval
94
+
95
+ def get_total_time(self, to_str=True):
96
+ total_time = time.time() - self.init_time
97
+ if to_str:
98
+ total_time = str(datetime.timedelta(
99
+ seconds=total_time))[:-5]
100
+ return total_time
101
+
102
+ def save_model(
103
+ self,
104
+ model,
105
+ optimizer,
106
+ name='model',
107
+ postfix='',
108
+ to_json=False):
109
+ # path
110
+ if postfix:
111
+ postfix = '_' + postfix
112
+ path_pt = os.path.join(
113
+ self.expdir , name+postfix+'.pt')
114
+
115
+ # check
116
+ print(' [*] model checkpoint saved: {}'.format(path_pt))
117
+
118
+ # save
119
+ if optimizer is not None:
120
+ torch.save({
121
+ 'global_step': self.global_step,
122
+ 'model': model.state_dict(),
123
+ 'optimizer': optimizer.state_dict()}, path_pt)
124
+ else:
125
+ torch.save({
126
+ 'global_step': self.global_step,
127
+ 'model': model.state_dict()}, path_pt)
128
+
129
+ # to json
130
+ if to_json:
131
+ path_json = os.path.join(
132
+ self.expdir , name+'.json')
133
+ utils.to_json(path_params, path_json)
134
+
135
+ def delete_model(self, name='model', postfix=''):
136
+ # path
137
+ if postfix:
138
+ postfix = '_' + postfix
139
+ path_pt = os.path.join(
140
+ self.expdir , name+postfix+'.pt')
141
+
142
+ # delete
143
+ if os.path.exists(path_pt):
144
+ os.remove(path_pt)
145
+ print(' [*] model checkpoint deleted: {}'.format(path_pt))
146
+
147
+ def global_step_increment(self):
148
+ self.global_step += 1
149
+
150
+
diffusion/logger/utils.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import yaml
3
+ import json
4
+ import pickle
5
+ import torch
6
+
7
+ def traverse_dir(
8
+ root_dir,
9
+ extensions,
10
+ amount=None,
11
+ str_include=None,
12
+ str_exclude=None,
13
+ is_pure=False,
14
+ is_sort=False,
15
+ is_ext=True):
16
+
17
+ file_list = []
18
+ cnt = 0
19
+ for root, _, files in os.walk(root_dir):
20
+ for file in files:
21
+ if any([file.endswith(f".{ext}") for ext in extensions]):
22
+ # path
23
+ mix_path = os.path.join(root, file)
24
+ pure_path = mix_path[len(root_dir)+1:] if is_pure else mix_path
25
+
26
+ # amount
27
+ if (amount is not None) and (cnt == amount):
28
+ if is_sort:
29
+ file_list.sort()
30
+ return file_list
31
+
32
+ # check string
33
+ if (str_include is not None) and (str_include not in pure_path):
34
+ continue
35
+ if (str_exclude is not None) and (str_exclude in pure_path):
36
+ continue
37
+
38
+ if not is_ext:
39
+ ext = pure_path.split('.')[-1]
40
+ pure_path = pure_path[:-(len(ext)+1)]
41
+ file_list.append(pure_path)
42
+ cnt += 1
43
+ if is_sort:
44
+ file_list.sort()
45
+ return file_list
46
+
47
+
48
+
49
+ class DotDict(dict):
50
+ def __getattr__(*args):
51
+ val = dict.get(*args)
52
+ return DotDict(val) if type(val) is dict else val
53
+
54
+ __setattr__ = dict.__setitem__
55
+ __delattr__ = dict.__delitem__
56
+
57
+
58
+ def get_network_paras_amount(model_dict):
59
+ info = dict()
60
+ for model_name, model in model_dict.items():
61
+ # all_params = sum(p.numel() for p in model.parameters())
62
+ trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
63
+
64
+ info[model_name] = trainable_params
65
+ return info
66
+
67
+
68
+ def load_config(path_config):
69
+ with open(path_config, "r") as config:
70
+ args = yaml.safe_load(config)
71
+ args = DotDict(args)
72
+ # print(args)
73
+ return args
74
+
75
+ def save_config(path_config,config):
76
+ config = dict(config)
77
+ with open(path_config, "w") as f:
78
+ yaml.dump(config, f)
79
+
80
+ def to_json(path_params, path_json):
81
+ params = torch.load(path_params, map_location=torch.device('cpu'))
82
+ raw_state_dict = {}
83
+ for k, v in params.items():
84
+ val = v.flatten().numpy().tolist()
85
+ raw_state_dict[k] = val
86
+
87
+ with open(path_json, 'w') as outfile:
88
+ json.dump(raw_state_dict, outfile,indent= "\t")
89
+
90
+
91
+ def convert_tensor_to_numpy(tensor, is_squeeze=True):
92
+ if is_squeeze:
93
+ tensor = tensor.squeeze()
94
+ if tensor.requires_grad:
95
+ tensor = tensor.detach()
96
+ if tensor.is_cuda:
97
+ tensor = tensor.cpu()
98
+ return tensor.numpy()
99
+
100
+
101
+ def load_model(
102
+ expdir,
103
+ model,
104
+ optimizer,
105
+ name='model',
106
+ postfix='',
107
+ device='cpu'):
108
+ if postfix == '':
109
+ postfix = '_' + postfix
110
+ path = os.path.join(expdir, name+postfix)
111
+ path_pt = traverse_dir(expdir, ['pt'], is_ext=False)
112
+ global_step = 0
113
+ if len(path_pt) > 0:
114
+ steps = [s[len(path):] for s in path_pt]
115
+ maxstep = max([int(s) if s.isdigit() else 0 for s in steps])
116
+ if maxstep >= 0:
117
+ path_pt = path+str(maxstep)+'.pt'
118
+ else:
119
+ path_pt = path+'best.pt'
120
+ print(' [*] restoring model from', path_pt)
121
+ ckpt = torch.load(path_pt, map_location=torch.device(device))
122
+ global_step = ckpt['global_step']
123
+ model.load_state_dict(ckpt['model'], strict=False)
124
+ if ckpt.get('optimizer') != None:
125
+ optimizer.load_state_dict(ckpt['optimizer'])
126
+ return global_step, model, optimizer
diffusion/onnx_export.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from diffusion_onnx import GaussianDiffusion
2
+ import os
3
+ import yaml
4
+ import torch
5
+ import torch.nn as nn
6
+ import numpy as np
7
+ from wavenet import WaveNet
8
+ import torch.nn.functional as F
9
+ import diffusion
10
+
11
+ class DotDict(dict):
12
+ def __getattr__(*args):
13
+ val = dict.get(*args)
14
+ return DotDict(val) if type(val) is dict else val
15
+
16
+ __setattr__ = dict.__setitem__
17
+ __delattr__ = dict.__delitem__
18
+
19
+
20
+ def load_model_vocoder(
21
+ model_path,
22
+ device='cpu'):
23
+ config_file = os.path.join(os.path.split(model_path)[0], 'config.yaml')
24
+ with open(config_file, "r") as config:
25
+ args = yaml.safe_load(config)
26
+ args = DotDict(args)
27
+
28
+ # load model
29
+ model = Unit2Mel(
30
+ args.data.encoder_out_channels,
31
+ args.model.n_spk,
32
+ args.model.use_pitch_aug,
33
+ 128,
34
+ args.model.n_layers,
35
+ args.model.n_chans,
36
+ args.model.n_hidden)
37
+
38
+ print(' [Loading] ' + model_path)
39
+ ckpt = torch.load(model_path, map_location=torch.device(device))
40
+ model.to(device)
41
+ model.load_state_dict(ckpt['model'])
42
+ model.eval()
43
+ return model, args
44
+
45
+
46
+ class Unit2Mel(nn.Module):
47
+ def __init__(
48
+ self,
49
+ input_channel,
50
+ n_spk,
51
+ use_pitch_aug=False,
52
+ out_dims=128,
53
+ n_layers=20,
54
+ n_chans=384,
55
+ n_hidden=256):
56
+ super().__init__()
57
+ self.unit_embed = nn.Linear(input_channel, n_hidden)
58
+ self.f0_embed = nn.Linear(1, n_hidden)
59
+ self.volume_embed = nn.Linear(1, n_hidden)
60
+ if use_pitch_aug:
61
+ self.aug_shift_embed = nn.Linear(1, n_hidden, bias=False)
62
+ else:
63
+ self.aug_shift_embed = None
64
+ self.n_spk = n_spk
65
+ if n_spk is not None and n_spk > 1:
66
+ self.spk_embed = nn.Embedding(n_spk, n_hidden)
67
+
68
+ # diffusion
69
+ self.decoder = GaussianDiffusion(out_dims, n_layers, n_chans, n_hidden)
70
+ self.hidden_size = n_hidden
71
+ self.speaker_map = torch.zeros((self.n_spk,1,1,n_hidden))
72
+
73
+
74
+
75
+ def forward(self, units, mel2ph, f0, volume, g = None):
76
+
77
+ '''
78
+ input:
79
+ B x n_frames x n_unit
80
+ return:
81
+ dict of B x n_frames x feat
82
+ '''
83
+
84
+ decoder_inp = F.pad(units, [0, 0, 1, 0])
85
+ mel2ph_ = mel2ph.unsqueeze(2).repeat([1, 1, units.shape[-1]])
86
+ units = torch.gather(decoder_inp, 1, mel2ph_) # [B, T, H]
87
+
88
+ x = self.unit_embed(units) + self.f0_embed((1 + f0.unsqueeze(-1) / 700).log()) + self.volume_embed(volume.unsqueeze(-1))
89
+
90
+ if self.n_spk is not None and self.n_spk > 1: # [N, S] * [S, B, 1, H]
91
+ g = g.reshape((g.shape[0], g.shape[1], 1, 1, 1)) # [N, S, B, 1, 1]
92
+ g = g * self.speaker_map # [N, S, B, 1, H]
93
+ g = torch.sum(g, dim=1) # [N, 1, B, 1, H]
94
+ g = g.transpose(0, -1).transpose(0, -2).squeeze(0) # [B, H, N]
95
+ x = x.transpose(1, 2) + g
96
+ return x
97
+ else:
98
+ return x.transpose(1, 2)
99
+
100
+
101
+ def init_spkembed(self, units, f0, volume, spk_id = None, spk_mix_dict = None, aug_shift = None,
102
+ gt_spec=None, infer=True, infer_speedup=10, method='dpm-solver', k_step=300, use_tqdm=True):
103
+
104
+ '''
105
+ input:
106
+ B x n_frames x n_unit
107
+ return:
108
+ dict of B x n_frames x feat
109
+ '''
110
+ x = self.unit_embed(units) + self.f0_embed((1+ f0 / 700).log()) + self.volume_embed(volume)
111
+ if self.n_spk is not None and self.n_spk > 1:
112
+ if spk_mix_dict is not None:
113
+ spk_embed_mix = torch.zeros((1,1,self.hidden_size))
114
+ for k, v in spk_mix_dict.items():
115
+ spk_id_torch = torch.LongTensor(np.array([[k]])).to(units.device)
116
+ spk_embeddd = self.spk_embed(spk_id_torch)
117
+ self.speaker_map[k] = spk_embeddd
118
+ spk_embed_mix = spk_embed_mix + v * spk_embeddd
119
+ x = x + spk_embed_mix
120
+ else:
121
+ x = x + self.spk_embed(spk_id - 1)
122
+ self.speaker_map = self.speaker_map.unsqueeze(0)
123
+ self.speaker_map = self.speaker_map.detach()
124
+ return x.transpose(1, 2)
125
+
126
+ def OnnxExport(self, project_name=None, init_noise=None, export_encoder=True, export_denoise=True, export_pred=True, export_after=True):
127
+ hubert_hidden_size = 768
128
+ n_frames = 100
129
+ hubert = torch.randn((1, n_frames, hubert_hidden_size))
130
+ mel2ph = torch.arange(end=n_frames).unsqueeze(0).long()
131
+ f0 = torch.randn((1, n_frames))
132
+ volume = torch.randn((1, n_frames))
133
+ spk_mix = []
134
+ spks = {}
135
+ if self.n_spk is not None and self.n_spk > 1:
136
+ for i in range(self.n_spk):
137
+ spk_mix.append(1.0/float(self.n_spk))
138
+ spks.update({i:1.0/float(self.n_spk)})
139
+ spk_mix = torch.tensor(spk_mix)
140
+ spk_mix = spk_mix.repeat(n_frames, 1)
141
+ orgouttt = self.init_spkembed(hubert, f0.unsqueeze(-1), volume.unsqueeze(-1), spk_mix_dict=spks)
142
+ outtt = self.forward(hubert, mel2ph, f0, volume, spk_mix)
143
+ if export_encoder:
144
+ torch.onnx.export(
145
+ self,
146
+ (hubert, mel2ph, f0, volume, spk_mix),
147
+ f"{project_name}_encoder.onnx",
148
+ input_names=["hubert", "mel2ph", "f0", "volume", "spk_mix"],
149
+ output_names=["mel_pred"],
150
+ dynamic_axes={
151
+ "hubert": [1],
152
+ "f0": [1],
153
+ "volume": [1],
154
+ "mel2ph": [1],
155
+ "spk_mix": [0],
156
+ },
157
+ opset_version=16
158
+ )
159
+
160
+ self.decoder.OnnxExport(project_name, init_noise=init_noise, export_denoise=export_denoise, export_pred=export_pred, export_after=export_after)
161
+
162
+ def ExportOnnx(self, project_name=None):
163
+ hubert_hidden_size = 768
164
+ n_frames = 100
165
+ hubert = torch.randn((1, n_frames, hubert_hidden_size))
166
+ mel2ph = torch.arange(end=n_frames).unsqueeze(0).long()
167
+ f0 = torch.randn((1, n_frames))
168
+ volume = torch.randn((1, n_frames))
169
+ spk_mix = []
170
+ spks = {}
171
+ if self.n_spk is not None and self.n_spk > 1:
172
+ for i in range(self.n_spk):
173
+ spk_mix.append(1.0/float(self.n_spk))
174
+ spks.update({i:1.0/float(self.n_spk)})
175
+ spk_mix = torch.tensor(spk_mix)
176
+ orgouttt = self.orgforward(hubert, f0.unsqueeze(-1), volume.unsqueeze(-1), spk_mix_dict=spks)
177
+ outtt = self.forward(hubert, mel2ph, f0, volume, spk_mix)
178
+
179
+ torch.onnx.export(
180
+ self,
181
+ (hubert, mel2ph, f0, volume, spk_mix),
182
+ f"{project_name}_encoder.onnx",
183
+ input_names=["hubert", "mel2ph", "f0", "volume", "spk_mix"],
184
+ output_names=["mel_pred"],
185
+ dynamic_axes={
186
+ "hubert": [1],
187
+ "f0": [1],
188
+ "volume": [1],
189
+ "mel2ph": [1]
190
+ },
191
+ opset_version=16
192
+ )
193
+
194
+ condition = torch.randn(1,self.decoder.n_hidden,n_frames)
195
+ noise = torch.randn((1, 1, self.decoder.mel_bins, condition.shape[2]), dtype=torch.float32)
196
+ pndm_speedup = torch.LongTensor([100])
197
+ K_steps = torch.LongTensor([1000])
198
+ self.decoder = torch.jit.script(self.decoder)
199
+ self.decoder(condition, noise, pndm_speedup, K_steps)
200
+
201
+ torch.onnx.export(
202
+ self.decoder,
203
+ (condition, noise, pndm_speedup, K_steps),
204
+ f"{project_name}_diffusion.onnx",
205
+ input_names=["condition", "noise", "pndm_speedup", "K_steps"],
206
+ output_names=["mel"],
207
+ dynamic_axes={
208
+ "condition": [2],
209
+ "noise": [3],
210
+ },
211
+ opset_version=16
212
+ )
213
+
214
+
215
+ if __name__ == "__main__":
216
+ project_name = "dddsp"
217
+ model_path = f'{project_name}/model_500000.pt'
218
+
219
+ model, _ = load_model_vocoder(model_path)
220
+
221
+ # 分开Diffusion导出(需要使用MoeSS/MoeVoiceStudio或者自己编写Pndm/Dpm采样)
222
+ model.OnnxExport(project_name, export_encoder=True, export_denoise=True, export_pred=True, export_after=True)
223
+
224
+ # 合并Diffusion导出(Encoder和Diffusion分开,直接将Encoder的结果和初始噪声输入Diffusion即可)
225
+ # model.ExportOnnx(project_name)
226
+
diffusion/solver.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ import numpy as np
4
+ import torch
5
+ import librosa
6
+ from diffusion.logger.saver import Saver
7
+ from diffusion.logger import utils
8
+ from torch import autocast
9
+ from torch.cuda.amp import GradScaler
10
+
11
+ def test(args, model, vocoder, loader_test, saver):
12
+ print(' [*] testing...')
13
+ model.eval()
14
+
15
+ # losses
16
+ test_loss = 0.
17
+
18
+ # intialization
19
+ num_batches = len(loader_test)
20
+ rtf_all = []
21
+
22
+ # run
23
+ with torch.no_grad():
24
+ for bidx, data in enumerate(loader_test):
25
+ fn = data['name'][0].split("/")[-1]
26
+ speaker = data['name'][0].split("/")[-2]
27
+ print('--------')
28
+ print('{}/{} - {}'.format(bidx, num_batches, fn))
29
+
30
+ # unpack data
31
+ for k in data.keys():
32
+ if not k.startswith('name'):
33
+ data[k] = data[k].to(args.device)
34
+ print('>>', data['name'][0])
35
+
36
+ # forward
37
+ st_time = time.time()
38
+ mel = model(
39
+ data['units'],
40
+ data['f0'],
41
+ data['volume'],
42
+ data['spk_id'],
43
+ gt_spec=None,
44
+ infer=True,
45
+ infer_speedup=args.infer.speedup,
46
+ method=args.infer.method)
47
+ signal = vocoder.infer(mel, data['f0'])
48
+ ed_time = time.time()
49
+
50
+ # RTF
51
+ run_time = ed_time - st_time
52
+ song_time = signal.shape[-1] / args.data.sampling_rate
53
+ rtf = run_time / song_time
54
+ print('RTF: {} | {} / {}'.format(rtf, run_time, song_time))
55
+ rtf_all.append(rtf)
56
+
57
+ # loss
58
+ for i in range(args.train.batch_size):
59
+ loss = model(
60
+ data['units'],
61
+ data['f0'],
62
+ data['volume'],
63
+ data['spk_id'],
64
+ gt_spec=data['mel'],
65
+ infer=False)
66
+ test_loss += loss.item()
67
+
68
+ # log mel
69
+ saver.log_spec(f"{speaker}_{fn}.wav", data['mel'], mel)
70
+
71
+ # log audi
72
+ path_audio = data['name_ext'][0]
73
+ audio, sr = librosa.load(path_audio, sr=args.data.sampling_rate)
74
+ if len(audio.shape) > 1:
75
+ audio = librosa.to_mono(audio)
76
+ audio = torch.from_numpy(audio).unsqueeze(0).to(signal)
77
+ saver.log_audio({f"{speaker}_{fn}_gt.wav": audio,f"{speaker}_{fn}_pred.wav": signal})
78
+ # report
79
+ test_loss /= args.train.batch_size
80
+ test_loss /= num_batches
81
+
82
+ # check
83
+ print(' [test_loss] test_loss:', test_loss)
84
+ print(' Real Time Factor', np.mean(rtf_all))
85
+ return test_loss
86
+
87
+
88
+ def train(args, initial_global_step, model, optimizer, scheduler, vocoder, loader_train, loader_test):
89
+ # saver
90
+ saver = Saver(args, initial_global_step=initial_global_step)
91
+
92
+ # model size
93
+ params_count = utils.get_network_paras_amount({'model': model})
94
+ saver.log_info('--- model size ---')
95
+ saver.log_info(params_count)
96
+
97
+ # run
98
+ num_batches = len(loader_train)
99
+ model.train()
100
+ saver.log_info('======= start training =======')
101
+ scaler = GradScaler()
102
+ if args.train.amp_dtype == 'fp32':
103
+ dtype = torch.float32
104
+ elif args.train.amp_dtype == 'fp16':
105
+ dtype = torch.float16
106
+ elif args.train.amp_dtype == 'bf16':
107
+ dtype = torch.bfloat16
108
+ else:
109
+ raise ValueError(' [x] Unknown amp_dtype: ' + args.train.amp_dtype)
110
+ saver.log_info("epoch|batch_idx/num_batches|output_dir|batch/s|lr|time|step")
111
+ for epoch in range(args.train.epochs):
112
+ for batch_idx, data in enumerate(loader_train):
113
+ saver.global_step_increment()
114
+ optimizer.zero_grad()
115
+
116
+ # unpack data
117
+ for k in data.keys():
118
+ if not k.startswith('name'):
119
+ data[k] = data[k].to(args.device)
120
+
121
+ # forward
122
+ if dtype == torch.float32:
123
+ loss = model(data['units'].float(), data['f0'], data['volume'], data['spk_id'],
124
+ aug_shift = data['aug_shift'], gt_spec=data['mel'].float(), infer=False)
125
+ else:
126
+ with autocast(device_type=args.device, dtype=dtype):
127
+ loss = model(data['units'], data['f0'], data['volume'], data['spk_id'],
128
+ aug_shift = data['aug_shift'], gt_spec=data['mel'], infer=False)
129
+
130
+ # handle nan loss
131
+ if torch.isnan(loss):
132
+ raise ValueError(' [x] nan loss ')
133
+ else:
134
+ # backpropagate
135
+ if dtype == torch.float32:
136
+ loss.backward()
137
+ optimizer.step()
138
+ else:
139
+ scaler.scale(loss).backward()
140
+ scaler.step(optimizer)
141
+ scaler.update()
142
+ scheduler.step()
143
+
144
+ # log loss
145
+ if saver.global_step % args.train.interval_log == 0:
146
+ current_lr = optimizer.param_groups[0]['lr']
147
+ saver.log_info(
148
+ 'epoch: {} | {:3d}/{:3d} | {} | batch/s: {:.2f} | lr: {:.6} | loss: {:.3f} | time: {} | step: {}'.format(
149
+ epoch,
150
+ batch_idx,
151
+ num_batches,
152
+ args.env.expdir,
153
+ args.train.interval_log/saver.get_interval_time(),
154
+ current_lr,
155
+ loss.item(),
156
+ saver.get_total_time(),
157
+ saver.global_step
158
+ )
159
+ )
160
+
161
+ saver.log_value({
162
+ 'train/loss': loss.item()
163
+ })
164
+
165
+ saver.log_value({
166
+ 'train/lr': current_lr
167
+ })
168
+
169
+ # validation
170
+ if saver.global_step % args.train.interval_val == 0:
171
+ optimizer_save = optimizer if args.train.save_opt else None
172
+
173
+ # save latest
174
+ saver.save_model(model, optimizer_save, postfix=f'{saver.global_step}')
175
+ last_val_step = saver.global_step - args.train.interval_val
176
+ if last_val_step % args.train.interval_force_save != 0:
177
+ saver.delete_model(postfix=f'{last_val_step}')
178
+
179
+ # run testing set
180
+ test_loss = test(args, model, vocoder, loader_test, saver)
181
+
182
+ # log loss
183
+ saver.log_info(
184
+ ' --- <validation> --- \nloss: {:.3f}. '.format(
185
+ test_loss,
186
+ )
187
+ )
188
+
189
+ saver.log_value({
190
+ 'validation/loss': test_loss
191
+ })
192
+
193
+ model.train()
194
+
195
+
diffusion/unit2mel.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import yaml
3
+ import torch
4
+ import torch.nn as nn
5
+ import numpy as np
6
+ from .diffusion import GaussianDiffusion
7
+ from .wavenet import WaveNet
8
+ from .vocoder import Vocoder
9
+
10
+ class DotDict(dict):
11
+ def __getattr__(*args):
12
+ val = dict.get(*args)
13
+ return DotDict(val) if type(val) is dict else val
14
+
15
+ __setattr__ = dict.__setitem__
16
+ __delattr__ = dict.__delitem__
17
+
18
+
19
+ def load_model_vocoder(
20
+ model_path,
21
+ device='cpu',
22
+ config_path = None
23
+ ):
24
+ if config_path is None: config_file = os.path.join(os.path.split(model_path)[0], 'config.yaml')
25
+ else: config_file = config_path
26
+
27
+ with open(config_file, "r") as config:
28
+ args = yaml.safe_load(config)
29
+ args = DotDict(args)
30
+
31
+ # load vocoder
32
+ vocoder = Vocoder(args.vocoder.type, args.vocoder.ckpt, device=device)
33
+
34
+ # load model
35
+ model = Unit2Mel(
36
+ args.data.encoder_out_channels,
37
+ args.model.n_spk,
38
+ args.model.use_pitch_aug,
39
+ vocoder.dimension,
40
+ args.model.n_layers,
41
+ args.model.n_chans,
42
+ args.model.n_hidden)
43
+
44
+ print(' [Loading] ' + model_path)
45
+ ckpt = torch.load(model_path, map_location=torch.device(device))
46
+ model.to(device)
47
+ model.load_state_dict(ckpt['model'])
48
+ model.eval()
49
+ return model, vocoder, args
50
+
51
+
52
+ class Unit2Mel(nn.Module):
53
+ def __init__(
54
+ self,
55
+ input_channel,
56
+ n_spk,
57
+ use_pitch_aug=False,
58
+ out_dims=128,
59
+ n_layers=20,
60
+ n_chans=384,
61
+ n_hidden=256):
62
+ super().__init__()
63
+ self.unit_embed = nn.Linear(input_channel, n_hidden)
64
+ self.f0_embed = nn.Linear(1, n_hidden)
65
+ self.volume_embed = nn.Linear(1, n_hidden)
66
+ if use_pitch_aug:
67
+ self.aug_shift_embed = nn.Linear(1, n_hidden, bias=False)
68
+ else:
69
+ self.aug_shift_embed = None
70
+ self.n_spk = n_spk
71
+ if n_spk is not None and n_spk > 1:
72
+ self.spk_embed = nn.Embedding(n_spk, n_hidden)
73
+
74
+ self.n_hidden = n_hidden
75
+ # diffusion
76
+ self.decoder = GaussianDiffusion(WaveNet(out_dims, n_layers, n_chans, n_hidden), out_dims=out_dims)
77
+ self.input_channel = input_channel
78
+
79
+ def init_spkembed(self, units, f0, volume, spk_id = None, spk_mix_dict = None, aug_shift = None,
80
+ gt_spec=None, infer=True, infer_speedup=10, method='dpm-solver', k_step=300, use_tqdm=True):
81
+
82
+ '''
83
+ input:
84
+ B x n_frames x n_unit
85
+ return:
86
+ dict of B x n_frames x feat
87
+ '''
88
+ x = self.unit_embed(units) + self.f0_embed((1+ f0 / 700).log()) + self.volume_embed(volume)
89
+ if self.n_spk is not None and self.n_spk > 1:
90
+ if spk_mix_dict is not None:
91
+ spk_embed_mix = torch.zeros((1,1,self.hidden_size))
92
+ for k, v in spk_mix_dict.items():
93
+ spk_id_torch = torch.LongTensor(np.array([[k]])).to(units.device)
94
+ spk_embeddd = self.spk_embed(spk_id_torch)
95
+ self.speaker_map[k] = spk_embeddd
96
+ spk_embed_mix = spk_embed_mix + v * spk_embeddd
97
+ x = x + spk_embed_mix
98
+ else:
99
+ x = x + self.spk_embed(spk_id - 1)
100
+ self.speaker_map = self.speaker_map.unsqueeze(0)
101
+ self.speaker_map = self.speaker_map.detach()
102
+ return x.transpose(1, 2)
103
+
104
+ def init_spkmix(self, n_spk):
105
+ self.speaker_map = torch.zeros((n_spk,1,1,self.n_hidden))
106
+ hubert_hidden_size = self.input_channel
107
+ n_frames = 10
108
+ hubert = torch.randn((1, n_frames, hubert_hidden_size))
109
+ mel2ph = torch.arange(end=n_frames).unsqueeze(0).long()
110
+ f0 = torch.randn((1, n_frames))
111
+ volume = torch.randn((1, n_frames))
112
+ spks = {}
113
+ for i in range(n_spk):
114
+ spks.update({i:1.0/float(self.n_spk)})
115
+ orgouttt = self.init_spkembed(hubert, f0.unsqueeze(-1), volume.unsqueeze(-1), spk_mix_dict=spks)
116
+
117
+ def forward(self, units, f0, volume, spk_id = None, spk_mix_dict = None, aug_shift = None,
118
+ gt_spec=None, infer=True, infer_speedup=10, method='dpm-solver', k_step=300, use_tqdm=True):
119
+
120
+ '''
121
+ input:
122
+ B x n_frames x n_unit
123
+ return:
124
+ dict of B x n_frames x feat
125
+ '''
126
+
127
+ x = self.unit_embed(units) + self.f0_embed((1+ f0 / 700).log()) + self.volume_embed(volume)
128
+ if self.n_spk is not None and self.n_spk > 1:
129
+ if spk_mix_dict is not None:
130
+ for k, v in spk_mix_dict.items():
131
+ spk_id_torch = torch.LongTensor(np.array([[k]])).to(units.device)
132
+ x = x + v * self.spk_embed(spk_id_torch)
133
+ else:
134
+ if spk_id.shape[1] > 1:
135
+ g = spk_id.reshape((spk_id.shape[0], spk_id.shape[1], 1, 1, 1)) # [N, S, B, 1, 1]
136
+ g = g * self.speaker_map # [N, S, B, 1, H]
137
+ g = torch.sum(g, dim=1) # [N, 1, B, 1, H]
138
+ g = g.transpose(0, -1).transpose(0, -2).squeeze(0) # [B, H, N]
139
+ x = x + g
140
+ else:
141
+ x = x + self.spk_embed(spk_id)
142
+ if self.aug_shift_embed is not None and aug_shift is not None:
143
+ x = x + self.aug_shift_embed(aug_shift / 5)
144
+ x = self.decoder(x, gt_spec=gt_spec, infer=infer, infer_speedup=infer_speedup, method=method, k_step=k_step, use_tqdm=use_tqdm)
145
+
146
+ return x
147
+
diffusion/vocoder.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from vdecoder.nsf_hifigan.nvSTFT import STFT
3
+ from vdecoder.nsf_hifigan.models import load_model,load_config
4
+ from torchaudio.transforms import Resample
5
+
6
+
7
+ class Vocoder:
8
+ def __init__(self, vocoder_type, vocoder_ckpt, device = None):
9
+ if device is None:
10
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
11
+ self.device = device
12
+
13
+ if vocoder_type == 'nsf-hifigan':
14
+ self.vocoder = NsfHifiGAN(vocoder_ckpt, device = device)
15
+ elif vocoder_type == 'nsf-hifigan-log10':
16
+ self.vocoder = NsfHifiGANLog10(vocoder_ckpt, device = device)
17
+ else:
18
+ raise ValueError(f" [x] Unknown vocoder: {vocoder_type}")
19
+
20
+ self.resample_kernel = {}
21
+ self.vocoder_sample_rate = self.vocoder.sample_rate()
22
+ self.vocoder_hop_size = self.vocoder.hop_size()
23
+ self.dimension = self.vocoder.dimension()
24
+
25
+ def extract(self, audio, sample_rate, keyshift=0):
26
+
27
+ # resample
28
+ if sample_rate == self.vocoder_sample_rate:
29
+ audio_res = audio
30
+ else:
31
+ key_str = str(sample_rate)
32
+ if key_str not in self.resample_kernel:
33
+ self.resample_kernel[key_str] = Resample(sample_rate, self.vocoder_sample_rate, lowpass_filter_width = 128).to(self.device)
34
+ audio_res = self.resample_kernel[key_str](audio)
35
+
36
+ # extract
37
+ mel = self.vocoder.extract(audio_res, keyshift=keyshift) # B, n_frames, bins
38
+ return mel
39
+
40
+ def infer(self, mel, f0):
41
+ f0 = f0[:,:mel.size(1),0] # B, n_frames
42
+ audio = self.vocoder(mel, f0)
43
+ return audio
44
+
45
+
46
+ class NsfHifiGAN(torch.nn.Module):
47
+ def __init__(self, model_path, device=None):
48
+ super().__init__()
49
+ if device is None:
50
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
51
+ self.device = device
52
+ self.model_path = model_path
53
+ self.model = None
54
+ self.h = load_config(model_path)
55
+ self.stft = STFT(
56
+ self.h.sampling_rate,
57
+ self.h.num_mels,
58
+ self.h.n_fft,
59
+ self.h.win_size,
60
+ self.h.hop_size,
61
+ self.h.fmin,
62
+ self.h.fmax)
63
+
64
+ def sample_rate(self):
65
+ return self.h.sampling_rate
66
+
67
+ def hop_size(self):
68
+ return self.h.hop_size
69
+
70
+ def dimension(self):
71
+ return self.h.num_mels
72
+
73
+ def extract(self, audio, keyshift=0):
74
+ mel = self.stft.get_mel(audio, keyshift=keyshift).transpose(1, 2) # B, n_frames, bins
75
+ return mel
76
+
77
+ def forward(self, mel, f0):
78
+ if self.model is None:
79
+ print('| Load HifiGAN: ', self.model_path)
80
+ self.model, self.h = load_model(self.model_path, device=self.device)
81
+ with torch.no_grad():
82
+ c = mel.transpose(1, 2)
83
+ audio = self.model(c, f0)
84
+ return audio
85
+
86
+ class NsfHifiGANLog10(NsfHifiGAN):
87
+ def forward(self, mel, f0):
88
+ if self.model is None:
89
+ print('| Load HifiGAN: ', self.model_path)
90
+ self.model, self.h = load_model(self.model_path, device=self.device)
91
+ with torch.no_grad():
92
+ c = 0.434294 * mel.transpose(1, 2)
93
+ audio = self.model(c, f0)
94
+ return audio
diffusion/wavenet.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from math import sqrt
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+ from torch.nn import Mish
8
+
9
+
10
+ class Conv1d(torch.nn.Conv1d):
11
+ def __init__(self, *args, **kwargs):
12
+ super().__init__(*args, **kwargs)
13
+ nn.init.kaiming_normal_(self.weight)
14
+
15
+
16
+ class SinusoidalPosEmb(nn.Module):
17
+ def __init__(self, dim):
18
+ super().__init__()
19
+ self.dim = dim
20
+
21
+ def forward(self, x):
22
+ device = x.device
23
+ half_dim = self.dim // 2
24
+ emb = math.log(10000) / (half_dim - 1)
25
+ emb = torch.exp(torch.arange(half_dim, device=device) * -emb)
26
+ emb = x[:, None] * emb[None, :]
27
+ emb = torch.cat((emb.sin(), emb.cos()), dim=-1)
28
+ return emb
29
+
30
+
31
+ class ResidualBlock(nn.Module):
32
+ def __init__(self, encoder_hidden, residual_channels, dilation):
33
+ super().__init__()
34
+ self.residual_channels = residual_channels
35
+ self.dilated_conv = nn.Conv1d(
36
+ residual_channels,
37
+ 2 * residual_channels,
38
+ kernel_size=3,
39
+ padding=dilation,
40
+ dilation=dilation
41
+ )
42
+ self.diffusion_projection = nn.Linear(residual_channels, residual_channels)
43
+ self.conditioner_projection = nn.Conv1d(encoder_hidden, 2 * residual_channels, 1)
44
+ self.output_projection = nn.Conv1d(residual_channels, 2 * residual_channels, 1)
45
+
46
+ def forward(self, x, conditioner, diffusion_step):
47
+ diffusion_step = self.diffusion_projection(diffusion_step).unsqueeze(-1)
48
+ conditioner = self.conditioner_projection(conditioner)
49
+ y = x + diffusion_step
50
+
51
+ y = self.dilated_conv(y) + conditioner
52
+
53
+ # Using torch.split instead of torch.chunk to avoid using onnx::Slice
54
+ gate, filter = torch.split(y, [self.residual_channels, self.residual_channels], dim=1)
55
+ y = torch.sigmoid(gate) * torch.tanh(filter)
56
+
57
+ y = self.output_projection(y)
58
+
59
+ # Using torch.split instead of torch.chunk to avoid using onnx::Slice
60
+ residual, skip = torch.split(y, [self.residual_channels, self.residual_channels], dim=1)
61
+ return (x + residual) / math.sqrt(2.0), skip
62
+
63
+
64
+ class WaveNet(nn.Module):
65
+ def __init__(self, in_dims=128, n_layers=20, n_chans=384, n_hidden=256):
66
+ super().__init__()
67
+ self.input_projection = Conv1d(in_dims, n_chans, 1)
68
+ self.diffusion_embedding = SinusoidalPosEmb(n_chans)
69
+ self.mlp = nn.Sequential(
70
+ nn.Linear(n_chans, n_chans * 4),
71
+ Mish(),
72
+ nn.Linear(n_chans * 4, n_chans)
73
+ )
74
+ self.residual_layers = nn.ModuleList([
75
+ ResidualBlock(
76
+ encoder_hidden=n_hidden,
77
+ residual_channels=n_chans,
78
+ dilation=1
79
+ )
80
+ for i in range(n_layers)
81
+ ])
82
+ self.skip_projection = Conv1d(n_chans, n_chans, 1)
83
+ self.output_projection = Conv1d(n_chans, in_dims, 1)
84
+ nn.init.zeros_(self.output_projection.weight)
85
+
86
+ def forward(self, spec, diffusion_step, cond):
87
+ """
88
+ :param spec: [B, 1, M, T]
89
+ :param diffusion_step: [B, 1]
90
+ :param cond: [B, M, T]
91
+ :return:
92
+ """
93
+ x = spec.squeeze(1)
94
+ x = self.input_projection(x) # [B, residual_channel, T]
95
+
96
+ x = F.relu(x)
97
+ diffusion_step = self.diffusion_embedding(diffusion_step)
98
+ diffusion_step = self.mlp(diffusion_step)
99
+ skip = []
100
+ for layer in self.residual_layers:
101
+ x, skip_connection = layer(x, cond, diffusion_step)
102
+ skip.append(skip_connection)
103
+
104
+ x = torch.sum(torch.stack(skip), dim=0) / sqrt(len(self.residual_layers))
105
+ x = self.skip_projection(x)
106
+ x = F.relu(x)
107
+ x = self.output_projection(x) # [B, mel_bins, T]
108
+ return x[:, None, :, :]
filelists/test.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ ./dataset/44k/taffy/000562.wav
2
+ ./dataset/44k/nyaru/000011.wav
3
+ ./dataset/44k/nyaru/000008.wav
4
+ ./dataset/44k/taffy/000563.wav
filelists/train.txt ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ./dataset/44k/taffy/000549.wav
2
+ ./dataset/44k/nyaru/000004.wav
3
+ ./dataset/44k/nyaru/000006.wav
4
+ ./dataset/44k/taffy/000551.wav
5
+ ./dataset/44k/nyaru/000009.wav
6
+ ./dataset/44k/taffy/000561.wav
7
+ ./dataset/44k/nyaru/000001.wav
8
+ ./dataset/44k/taffy/000553.wav
9
+ ./dataset/44k/nyaru/000002.wav
10
+ ./dataset/44k/taffy/000560.wav
11
+ ./dataset/44k/taffy/000557.wav
12
+ ./dataset/44k/nyaru/000005.wav
13
+ ./dataset/44k/taffy/000554.wav
14
+ ./dataset/44k/taffy/000550.wav
15
+ ./dataset/44k/taffy/000559.wav
filelists/val.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ ./dataset/44k/nyaru/000003.wav
2
+ ./dataset/44k/nyaru/000007.wav
3
+ ./dataset/44k/taffy/000558.wav
4
+ ./dataset/44k/taffy/000556.wav
flask_api.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import logging
3
+
4
+ import soundfile
5
+ import torch
6
+ import torchaudio
7
+ from flask import Flask, request, send_file
8
+ from flask_cors import CORS
9
+
10
+ from inference.infer_tool import Svc, RealTimeVC
11
+
12
+ app = Flask(__name__)
13
+
14
+ CORS(app)
15
+
16
+ logging.getLogger('numba').setLevel(logging.WARNING)
17
+
18
+
19
+ @app.route("/voiceChangeModel", methods=["POST"])
20
+ def voice_change_model():
21
+ request_form = request.form
22
+ wave_file = request.files.get("sample", None)
23
+ # 变调信息
24
+ f_pitch_change = float(request_form.get("fPitchChange", 0))
25
+ # DAW所需的采样率
26
+ daw_sample = int(float(request_form.get("sampleRate", 0)))
27
+ speaker_id = int(float(request_form.get("sSpeakId", 0)))
28
+ # http获得wav文件并转换
29
+ input_wav_path = io.BytesIO(wave_file.read())
30
+
31
+ # 模型推理
32
+ if raw_infer:
33
+ # out_audio, out_sr = svc_model.infer(speaker_id, f_pitch_change, input_wav_path)
34
+ out_audio, out_sr = svc_model.infer(speaker_id, f_pitch_change, input_wav_path, cluster_infer_ratio=0,
35
+ auto_predict_f0=False, noice_scale=0.4, f0_filter=False)
36
+ tar_audio = torchaudio.functional.resample(out_audio, svc_model.target_sample, daw_sample)
37
+ else:
38
+ out_audio = svc.process(svc_model, speaker_id, f_pitch_change, input_wav_path, cluster_infer_ratio=0,
39
+ auto_predict_f0=False, noice_scale=0.4, f0_filter=False)
40
+ tar_audio = torchaudio.functional.resample(torch.from_numpy(out_audio), svc_model.target_sample, daw_sample)
41
+ # 返回音频
42
+ out_wav_path = io.BytesIO()
43
+ soundfile.write(out_wav_path, tar_audio.cpu().numpy(), daw_sample, format="wav")
44
+ out_wav_path.seek(0)
45
+ return send_file(out_wav_path, download_name="temp.wav", as_attachment=True)
46
+
47
+
48
+ if __name__ == '__main__':
49
+ # 启用则为直接切片合成,False为交叉淡化方式
50
+ # vst插件调整0.3-0.5s切片时间可以降低延迟,直接切片方法会有连接处爆音、交叉淡化会有轻微重叠声音
51
+ # 自行选择能接受的方法,或将vst最大切片时间调整为1s,此处设为Ture,延迟大音质稳定一些
52
+ raw_infer = True
53
+ # 每个模型和config是唯一对应的
54
+ model_name = "logs/32k/G_174000-Copy1.pth"
55
+ config_name = "configs/config.json"
56
+ cluster_model_path = "logs/44k/kmeans_10000.pt"
57
+ svc_model = Svc(model_name, config_name, cluster_model_path=cluster_model_path)
58
+ svc = RealTimeVC()
59
+ # 此处与vst插件对应,不建议更改
60
+ app.run(port=6842, host="0.0.0.0", debug=False, threaded=False)
hubert/__init__.py ADDED
File without changes
hubert/checkpoint_best_legacy_500.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:60d936ec5a566776fc392e69ad8b630d14eb588111233fe313436e200a7b187b
3
+ size 1330114945
hubert/hubert_model.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import random
3
+ from typing import Optional, Tuple
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+ import torch.nn.functional as t_func
8
+ from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
9
+
10
+
11
+ class Hubert(nn.Module):
12
+ def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
13
+ super().__init__()
14
+ self._mask = mask
15
+ self.feature_extractor = FeatureExtractor()
16
+ self.feature_projection = FeatureProjection()
17
+ self.positional_embedding = PositionalConvEmbedding()
18
+ self.norm = nn.LayerNorm(768)
19
+ self.dropout = nn.Dropout(0.1)
20
+ self.encoder = TransformerEncoder(
21
+ nn.TransformerEncoderLayer(
22
+ 768, 12, 3072, activation="gelu", batch_first=True
23
+ ),
24
+ 12,
25
+ )
26
+ self.proj = nn.Linear(768, 256)
27
+
28
+ self.masked_spec_embed = nn.Parameter(torch.FloatTensor(768).uniform_())
29
+ self.label_embedding = nn.Embedding(num_label_embeddings, 256)
30
+
31
+ def mask(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
32
+ mask = None
33
+ if self.training and self._mask:
34
+ mask = _compute_mask((x.size(0), x.size(1)), 0.8, 10, x.device, 2)
35
+ x[mask] = self.masked_spec_embed.to(x.dtype)
36
+ return x, mask
37
+
38
+ def encode(
39
+ self, x: torch.Tensor, layer: Optional[int] = None
40
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
41
+ x = self.feature_extractor(x)
42
+ x = self.feature_projection(x.transpose(1, 2))
43
+ x, mask = self.mask(x)
44
+ x = x + self.positional_embedding(x)
45
+ x = self.dropout(self.norm(x))
46
+ x = self.encoder(x, output_layer=layer)
47
+ return x, mask
48
+
49
+ def logits(self, x: torch.Tensor) -> torch.Tensor:
50
+ logits = torch.cosine_similarity(
51
+ x.unsqueeze(2),
52
+ self.label_embedding.weight.unsqueeze(0).unsqueeze(0),
53
+ dim=-1,
54
+ )
55
+ return logits / 0.1
56
+
57
+ def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
58
+ x, mask = self.encode(x)
59
+ x = self.proj(x)
60
+ logits = self.logits(x)
61
+ return logits, mask
62
+
63
+
64
+ class HubertSoft(Hubert):
65
+ def __init__(self):
66
+ super().__init__()
67
+
68
+ @torch.inference_mode()
69
+ def units(self, wav: torch.Tensor) -> torch.Tensor:
70
+ wav = t_func.pad(wav, ((400 - 320) // 2, (400 - 320) // 2))
71
+ x, _ = self.encode(wav)
72
+ return self.proj(x)
73
+
74
+
75
+ class FeatureExtractor(nn.Module):
76
+ def __init__(self):
77
+ super().__init__()
78
+ self.conv0 = nn.Conv1d(1, 512, 10, 5, bias=False)
79
+ self.norm0 = nn.GroupNorm(512, 512)
80
+ self.conv1 = nn.Conv1d(512, 512, 3, 2, bias=False)
81
+ self.conv2 = nn.Conv1d(512, 512, 3, 2, bias=False)
82
+ self.conv3 = nn.Conv1d(512, 512, 3, 2, bias=False)
83
+ self.conv4 = nn.Conv1d(512, 512, 3, 2, bias=False)
84
+ self.conv5 = nn.Conv1d(512, 512, 2, 2, bias=False)
85
+ self.conv6 = nn.Conv1d(512, 512, 2, 2, bias=False)
86
+
87
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
88
+ x = t_func.gelu(self.norm0(self.conv0(x)))
89
+ x = t_func.gelu(self.conv1(x))
90
+ x = t_func.gelu(self.conv2(x))
91
+ x = t_func.gelu(self.conv3(x))
92
+ x = t_func.gelu(self.conv4(x))
93
+ x = t_func.gelu(self.conv5(x))
94
+ x = t_func.gelu(self.conv6(x))
95
+ return x
96
+
97
+
98
+ class FeatureProjection(nn.Module):
99
+ def __init__(self):
100
+ super().__init__()
101
+ self.norm = nn.LayerNorm(512)
102
+ self.projection = nn.Linear(512, 768)
103
+ self.dropout = nn.Dropout(0.1)
104
+
105
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
106
+ x = self.norm(x)
107
+ x = self.projection(x)
108
+ x = self.dropout(x)
109
+ return x
110
+
111
+
112
+ class PositionalConvEmbedding(nn.Module):
113
+ def __init__(self):
114
+ super().__init__()
115
+ self.conv = nn.Conv1d(
116
+ 768,
117
+ 768,
118
+ kernel_size=128,
119
+ padding=128 // 2,
120
+ groups=16,
121
+ )
122
+ self.conv = nn.utils.weight_norm(self.conv, name="weight", dim=2)
123
+
124
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
125
+ x = self.conv(x.transpose(1, 2))
126
+ x = t_func.gelu(x[:, :, :-1])
127
+ return x.transpose(1, 2)
128
+
129
+
130
+ class TransformerEncoder(nn.Module):
131
+ def __init__(
132
+ self, encoder_layer: nn.TransformerEncoderLayer, num_layers: int
133
+ ) -> None:
134
+ super(TransformerEncoder, self).__init__()
135
+ self.layers = nn.ModuleList(
136
+ [copy.deepcopy(encoder_layer) for _ in range(num_layers)]
137
+ )
138
+ self.num_layers = num_layers
139
+
140
+ def forward(
141
+ self,
142
+ src: torch.Tensor,
143
+ mask: torch.Tensor = None,
144
+ src_key_padding_mask: torch.Tensor = None,
145
+ output_layer: Optional[int] = None,
146
+ ) -> torch.Tensor:
147
+ output = src
148
+ for layer in self.layers[:output_layer]:
149
+ output = layer(
150
+ output, src_mask=mask, src_key_padding_mask=src_key_padding_mask
151
+ )
152
+ return output
153
+
154
+
155
+ def _compute_mask(
156
+ shape: Tuple[int, int],
157
+ mask_prob: float,
158
+ mask_length: int,
159
+ device: torch.device,
160
+ min_masks: int = 0,
161
+ ) -> torch.Tensor:
162
+ batch_size, sequence_length = shape
163
+
164
+ if mask_length < 1:
165
+ raise ValueError("`mask_length` has to be bigger than 0.")
166
+
167
+ if mask_length > sequence_length:
168
+ raise ValueError(
169
+ f"`mask_length` has to be smaller than `sequence_length`, but got `mask_length`: {mask_length} and `sequence_length`: {sequence_length}`"
170
+ )
171
+
172
+ # compute number of masked spans in batch
173
+ num_masked_spans = int(mask_prob * sequence_length / mask_length + random.random())
174
+ num_masked_spans = max(num_masked_spans, min_masks)
175
+
176
+ # make sure num masked indices <= sequence_length
177
+ if num_masked_spans * mask_length > sequence_length:
178
+ num_masked_spans = sequence_length // mask_length
179
+
180
+ # SpecAugment mask to fill
181
+ mask = torch.zeros((batch_size, sequence_length), device=device, dtype=torch.bool)
182
+
183
+ # uniform distribution to sample from, make sure that offset samples are < sequence_length
184
+ uniform_dist = torch.ones(
185
+ (batch_size, sequence_length - (mask_length - 1)), device=device
186
+ )
187
+
188
+ # get random indices to mask
189
+ mask_indices = torch.multinomial(uniform_dist, num_masked_spans)
190
+
191
+ # expand masked indices to masked spans
192
+ mask_indices = (
193
+ mask_indices.unsqueeze(dim=-1)
194
+ .expand((batch_size, num_masked_spans, mask_length))
195
+ .reshape(batch_size, num_masked_spans * mask_length)
196
+ )
197
+ offsets = (
198
+ torch.arange(mask_length, device=device)[None, None, :]
199
+ .expand((batch_size, num_masked_spans, mask_length))
200
+ .reshape(batch_size, num_masked_spans * mask_length)
201
+ )
202
+ mask_idxs = mask_indices + offsets
203
+
204
+ # scatter indices to mask
205
+ mask = mask.scatter(1, mask_idxs, True)
206
+
207
+ return mask
208
+
209
+
210
+ def hubert_soft(
211
+ path: str,
212
+ ) -> HubertSoft:
213
+ r"""HuBERT-Soft from `"A Comparison of Discrete and Soft Speech Units for Improved Voice Conversion"`.
214
+ Args:
215
+ path (str): path of a pretrained model
216
+ """
217
+ hubert = HubertSoft()
218
+ checkpoint = torch.load(path)
219
+ consume_prefix_in_state_dict_if_present(checkpoint, "module.")
220
+ hubert.load_state_dict(checkpoint)
221
+ hubert.eval()
222
+ return hubert
hubert/hubert_model_onnx.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import random
3
+ from typing import Optional, Tuple
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+ import torch.nn.functional as t_func
8
+ from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
9
+
10
+
11
+ class Hubert(nn.Module):
12
+ def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
13
+ super().__init__()
14
+ self._mask = mask
15
+ self.feature_extractor = FeatureExtractor()
16
+ self.feature_projection = FeatureProjection()
17
+ self.positional_embedding = PositionalConvEmbedding()
18
+ self.norm = nn.LayerNorm(768)
19
+ self.dropout = nn.Dropout(0.1)
20
+ self.encoder = TransformerEncoder(
21
+ nn.TransformerEncoderLayer(
22
+ 768, 12, 3072, activation="gelu", batch_first=True
23
+ ),
24
+ 12,
25
+ )
26
+ self.proj = nn.Linear(768, 256)
27
+
28
+ self.masked_spec_embed = nn.Parameter(torch.FloatTensor(768).uniform_())
29
+ self.label_embedding = nn.Embedding(num_label_embeddings, 256)
30
+
31
+ def mask(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
32
+ mask = None
33
+ if self.training and self._mask:
34
+ mask = _compute_mask((x.size(0), x.size(1)), 0.8, 10, x.device, 2)
35
+ x[mask] = self.masked_spec_embed.to(x.dtype)
36
+ return x, mask
37
+
38
+ def encode(
39
+ self, x: torch.Tensor, layer: Optional[int] = None
40
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
41
+ x = self.feature_extractor(x)
42
+ x = self.feature_projection(x.transpose(1, 2))
43
+ x, mask = self.mask(x)
44
+ x = x + self.positional_embedding(x)
45
+ x = self.dropout(self.norm(x))
46
+ x = self.encoder(x, output_layer=layer)
47
+ return x, mask
48
+
49
+ def logits(self, x: torch.Tensor) -> torch.Tensor:
50
+ logits = torch.cosine_similarity(
51
+ x.unsqueeze(2),
52
+ self.label_embedding.weight.unsqueeze(0).unsqueeze(0),
53
+ dim=-1,
54
+ )
55
+ return logits / 0.1
56
+
57
+
58
+ class HubertSoft(Hubert):
59
+ def __init__(self):
60
+ super().__init__()
61
+
62
+ def units(self, wav: torch.Tensor) -> torch.Tensor:
63
+ wav = t_func.pad(wav, ((400 - 320) // 2, (400 - 320) // 2))
64
+ x, _ = self.encode(wav)
65
+ return self.proj(x)
66
+
67
+ def forward(self, x):
68
+ return self.units(x)
69
+
70
+ class FeatureExtractor(nn.Module):
71
+ def __init__(self):
72
+ super().__init__()
73
+ self.conv0 = nn.Conv1d(1, 512, 10, 5, bias=False)
74
+ self.norm0 = nn.GroupNorm(512, 512)
75
+ self.conv1 = nn.Conv1d(512, 512, 3, 2, bias=False)
76
+ self.conv2 = nn.Conv1d(512, 512, 3, 2, bias=False)
77
+ self.conv3 = nn.Conv1d(512, 512, 3, 2, bias=False)
78
+ self.conv4 = nn.Conv1d(512, 512, 3, 2, bias=False)
79
+ self.conv5 = nn.Conv1d(512, 512, 2, 2, bias=False)
80
+ self.conv6 = nn.Conv1d(512, 512, 2, 2, bias=False)
81
+
82
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
83
+ x = t_func.gelu(self.norm0(self.conv0(x)))
84
+ x = t_func.gelu(self.conv1(x))
85
+ x = t_func.gelu(self.conv2(x))
86
+ x = t_func.gelu(self.conv3(x))
87
+ x = t_func.gelu(self.conv4(x))
88
+ x = t_func.gelu(self.conv5(x))
89
+ x = t_func.gelu(self.conv6(x))
90
+ return x
91
+
92
+
93
+ class FeatureProjection(nn.Module):
94
+ def __init__(self):
95
+ super().__init__()
96
+ self.norm = nn.LayerNorm(512)
97
+ self.projection = nn.Linear(512, 768)
98
+ self.dropout = nn.Dropout(0.1)
99
+
100
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
101
+ x = self.norm(x)
102
+ x = self.projection(x)
103
+ x = self.dropout(x)
104
+ return x
105
+
106
+
107
+ class PositionalConvEmbedding(nn.Module):
108
+ def __init__(self):
109
+ super().__init__()
110
+ self.conv = nn.Conv1d(
111
+ 768,
112
+ 768,
113
+ kernel_size=128,
114
+ padding=128 // 2,
115
+ groups=16,
116
+ )
117
+ self.conv = nn.utils.weight_norm(self.conv, name="weight", dim=2)
118
+
119
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
120
+ x = self.conv(x.transpose(1, 2))
121
+ x = t_func.gelu(x[:, :, :-1])
122
+ return x.transpose(1, 2)
123
+
124
+
125
+ class TransformerEncoder(nn.Module):
126
+ def __init__(
127
+ self, encoder_layer: nn.TransformerEncoderLayer, num_layers: int
128
+ ) -> None:
129
+ super(TransformerEncoder, self).__init__()
130
+ self.layers = nn.ModuleList(
131
+ [copy.deepcopy(encoder_layer) for _ in range(num_layers)]
132
+ )
133
+ self.num_layers = num_layers
134
+
135
+ def forward(
136
+ self,
137
+ src: torch.Tensor,
138
+ mask: torch.Tensor = None,
139
+ src_key_padding_mask: torch.Tensor = None,
140
+ output_layer: Optional[int] = None,
141
+ ) -> torch.Tensor:
142
+ output = src
143
+ for layer in self.layers[:output_layer]:
144
+ output = layer(
145
+ output, src_mask=mask, src_key_padding_mask=src_key_padding_mask
146
+ )
147
+ return output
148
+
149
+
150
+ def _compute_mask(
151
+ shape: Tuple[int, int],
152
+ mask_prob: float,
153
+ mask_length: int,
154
+ device: torch.device,
155
+ min_masks: int = 0,
156
+ ) -> torch.Tensor:
157
+ batch_size, sequence_length = shape
158
+
159
+ if mask_length < 1:
160
+ raise ValueError("`mask_length` has to be bigger than 0.")
161
+
162
+ if mask_length > sequence_length:
163
+ raise ValueError(
164
+ f"`mask_length` has to be smaller than `sequence_length`, but got `mask_length`: {mask_length} and `sequence_length`: {sequence_length}`"
165
+ )
166
+
167
+ # compute number of masked spans in batch
168
+ num_masked_spans = int(mask_prob * sequence_length / mask_length + random.random())
169
+ num_masked_spans = max(num_masked_spans, min_masks)
170
+
171
+ # make sure num masked indices <= sequence_length
172
+ if num_masked_spans * mask_length > sequence_length:
173
+ num_masked_spans = sequence_length // mask_length
174
+
175
+ # SpecAugment mask to fill
176
+ mask = torch.zeros((batch_size, sequence_length), device=device, dtype=torch.bool)
177
+
178
+ # uniform distribution to sample from, make sure that offset samples are < sequence_length
179
+ uniform_dist = torch.ones(
180
+ (batch_size, sequence_length - (mask_length - 1)), device=device
181
+ )
182
+
183
+ # get random indices to mask
184
+ mask_indices = torch.multinomial(uniform_dist, num_masked_spans)
185
+
186
+ # expand masked indices to masked spans
187
+ mask_indices = (
188
+ mask_indices.unsqueeze(dim=-1)
189
+ .expand((batch_size, num_masked_spans, mask_length))
190
+ .reshape(batch_size, num_masked_spans * mask_length)
191
+ )
192
+ offsets = (
193
+ torch.arange(mask_length, device=device)[None, None, :]
194
+ .expand((batch_size, num_masked_spans, mask_length))
195
+ .reshape(batch_size, num_masked_spans * mask_length)
196
+ )
197
+ mask_idxs = mask_indices + offsets
198
+
199
+ # scatter indices to mask
200
+ mask = mask.scatter(1, mask_idxs, True)
201
+
202
+ return mask
203
+
204
+
205
+ def hubert_soft(
206
+ path: str,
207
+ ) -> HubertSoft:
208
+ r"""HuBERT-Soft from `"A Comparison of Discrete and Soft Speech Units for Improved Voice Conversion"`.
209
+ Args:
210
+ path (str): path of a pretrained model
211
+ """
212
+ hubert = HubertSoft()
213
+ checkpoint = torch.load(path)
214
+ consume_prefix_in_state_dict_if_present(checkpoint, "module.")
215
+ hubert.load_state_dict(checkpoint)
216
+ hubert.eval()
217
+ return hubert
hubert/put_hubert_ckpt_here ADDED
File without changes
inference/__init__.py ADDED
File without changes
inference/chunks_temp.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"info": "temp_dict"}
inference/infer_tool.py ADDED
@@ -0,0 +1,533 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hashlib
2
+ import io
3
+ import json
4
+ import logging
5
+ import os
6
+ import time
7
+ from pathlib import Path
8
+ from inference import slicer
9
+ import gc
10
+
11
+ import librosa
12
+ import numpy as np
13
+ # import onnxruntime
14
+ import soundfile
15
+ import torch
16
+ import torchaudio
17
+
18
+ import cluster
19
+ import utils
20
+ from models import SynthesizerTrn
21
+ import pickle
22
+
23
+ from diffusion.unit2mel import load_model_vocoder
24
+ import yaml
25
+
26
+ logging.getLogger('matplotlib').setLevel(logging.WARNING)
27
+
28
+
29
+ def read_temp(file_name):
30
+ if not os.path.exists(file_name):
31
+ with open(file_name, "w") as f:
32
+ f.write(json.dumps({"info": "temp_dict"}))
33
+ return {}
34
+ else:
35
+ try:
36
+ with open(file_name, "r") as f:
37
+ data = f.read()
38
+ data_dict = json.loads(data)
39
+ if os.path.getsize(file_name) > 50 * 1024 * 1024:
40
+ f_name = file_name.replace("\\", "/").split("/")[-1]
41
+ print(f"clean {f_name}")
42
+ for wav_hash in list(data_dict.keys()):
43
+ if int(time.time()) - int(data_dict[wav_hash]["time"]) > 14 * 24 * 3600:
44
+ del data_dict[wav_hash]
45
+ except Exception as e:
46
+ print(e)
47
+ print(f"{file_name} error,auto rebuild file")
48
+ data_dict = {"info": "temp_dict"}
49
+ return data_dict
50
+
51
+
52
+ def write_temp(file_name, data):
53
+ with open(file_name, "w") as f:
54
+ f.write(json.dumps(data))
55
+
56
+
57
+ def timeit(func):
58
+ def run(*args, **kwargs):
59
+ t = time.time()
60
+ res = func(*args, **kwargs)
61
+ print('executing \'%s\' costed %.3fs' % (func.__name__, time.time() - t))
62
+ return res
63
+
64
+ return run
65
+
66
+
67
+ def format_wav(audio_path):
68
+ if Path(audio_path).suffix == '.wav':
69
+ return
70
+ raw_audio, raw_sample_rate = librosa.load(audio_path, mono=True, sr=None)
71
+ soundfile.write(Path(audio_path).with_suffix(".wav"), raw_audio, raw_sample_rate)
72
+
73
+
74
+ def get_end_file(dir_path, end):
75
+ file_lists = []
76
+ for root, dirs, files in os.walk(dir_path):
77
+ files = [f for f in files if f[0] != '.']
78
+ dirs[:] = [d for d in dirs if d[0] != '.']
79
+ for f_file in files:
80
+ if f_file.endswith(end):
81
+ file_lists.append(os.path.join(root, f_file).replace("\\", "/"))
82
+ return file_lists
83
+
84
+
85
+ def get_md5(content):
86
+ return hashlib.new("md5", content).hexdigest()
87
+
88
+ def fill_a_to_b(a, b):
89
+ if len(a) < len(b):
90
+ for _ in range(0, len(b) - len(a)):
91
+ a.append(a[0])
92
+
93
+ def mkdir(paths: list):
94
+ for path in paths:
95
+ if not os.path.exists(path):
96
+ os.mkdir(path)
97
+
98
+ def pad_array(arr, target_length):
99
+ current_length = arr.shape[0]
100
+ if current_length >= target_length:
101
+ return arr
102
+ else:
103
+ pad_width = target_length - current_length
104
+ pad_left = pad_width // 2
105
+ pad_right = pad_width - pad_left
106
+ padded_arr = np.pad(arr, (pad_left, pad_right), 'constant', constant_values=(0, 0))
107
+ return padded_arr
108
+
109
+ def split_list_by_n(list_collection, n, pre=0):
110
+ for i in range(0, len(list_collection), n):
111
+ yield list_collection[i-pre if i-pre>=0 else i: i + n]
112
+
113
+
114
+ class F0FilterException(Exception):
115
+ pass
116
+
117
+ class Svc(object):
118
+ def __init__(self, net_g_path, config_path,
119
+ device=None,
120
+ cluster_model_path="logs/44k/kmeans_10000.pt",
121
+ nsf_hifigan_enhance = False,
122
+ diffusion_model_path="logs/44k/diffusion/model_0.pt",
123
+ diffusion_config_path="configs/diffusion.yaml",
124
+ shallow_diffusion = False,
125
+ only_diffusion = False,
126
+ spk_mix_enable = False,
127
+ feature_retrieval = False
128
+ ):
129
+ self.net_g_path = net_g_path
130
+ self.only_diffusion = only_diffusion
131
+ self.shallow_diffusion = shallow_diffusion
132
+ self.feature_retrieval = feature_retrieval
133
+ if device is None:
134
+ self.dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")
135
+ else:
136
+ self.dev = torch.device(device)
137
+ self.net_g_ms = None
138
+ if not self.only_diffusion:
139
+ self.hps_ms = utils.get_hparams_from_file(config_path)
140
+ self.target_sample = self.hps_ms.data.sampling_rate
141
+ self.hop_size = self.hps_ms.data.hop_length
142
+ self.spk2id = self.hps_ms.spk
143
+ try:
144
+ self.vol_embedding = self.hps_ms.model.vol_embedding
145
+ except Exception as e:
146
+ self.vol_embedding = False
147
+ try:
148
+ self.speech_encoder = self.hps_ms.model.speech_encoder
149
+ except Exception as e:
150
+ self.speech_encoder = 'vec768l12'
151
+
152
+ self.nsf_hifigan_enhance = nsf_hifigan_enhance
153
+ if self.shallow_diffusion or self.only_diffusion:
154
+ if os.path.exists(diffusion_model_path) and os.path.exists(diffusion_model_path):
155
+ self.diffusion_model,self.vocoder,self.diffusion_args = load_model_vocoder(diffusion_model_path,self.dev,config_path=diffusion_config_path)
156
+ if self.only_diffusion:
157
+ self.target_sample = self.diffusion_args.data.sampling_rate
158
+ self.hop_size = self.diffusion_args.data.block_size
159
+ self.spk2id = self.diffusion_args.spk
160
+ self.speech_encoder = self.diffusion_args.data.encoder
161
+ if spk_mix_enable:
162
+ self.diffusion_model.init_spkmix(len(self.spk2id))
163
+ else:
164
+ print("No diffusion model or config found. Shallow diffusion mode will False")
165
+ self.shallow_diffusion = self.only_diffusion = False
166
+
167
+ # load hubert and model
168
+ if not self.only_diffusion:
169
+ self.load_model(spk_mix_enable)
170
+ self.hubert_model = utils.get_speech_encoder(self.speech_encoder,device=self.dev)
171
+ self.volume_extractor = utils.Volume_Extractor(self.hop_size)
172
+ else:
173
+ self.hubert_model = utils.get_speech_encoder(self.diffusion_args.data.encoder,device=self.dev)
174
+ self.volume_extractor = utils.Volume_Extractor(self.diffusion_args.data.block_size)
175
+
176
+ if os.path.exists(cluster_model_path):
177
+ if self.feature_retrieval:
178
+ with open(cluster_model_path,"rb") as f:
179
+ self.cluster_model = pickle.load(f)
180
+ self.big_npy = None
181
+ self.now_spk_id = -1
182
+ else:
183
+ self.cluster_model = cluster.get_cluster_model(cluster_model_path)
184
+ else:
185
+ self.feature_retrieval=False
186
+
187
+ if self.shallow_diffusion : self.nsf_hifigan_enhance = False
188
+ if self.nsf_hifigan_enhance:
189
+ from modules.enhancer import Enhancer
190
+ self.enhancer = Enhancer('nsf-hifigan', 'pretrain/nsf_hifigan/model',device=self.dev)
191
+
192
+ def load_model(self, spk_mix_enable=False):
193
+ # get model configuration
194
+ self.net_g_ms = SynthesizerTrn(
195
+ self.hps_ms.data.filter_length // 2 + 1,
196
+ self.hps_ms.train.segment_size // self.hps_ms.data.hop_length,
197
+ **self.hps_ms.model)
198
+ _ = utils.load_checkpoint(self.net_g_path, self.net_g_ms, None)
199
+ if "half" in self.net_g_path and torch.cuda.is_available():
200
+ _ = self.net_g_ms.half().eval().to(self.dev)
201
+ else:
202
+ _ = self.net_g_ms.eval().to(self.dev)
203
+ if spk_mix_enable:
204
+ self.net_g_ms.EnableCharacterMix(len(self.spk2id), self.dev)
205
+
206
+ def get_unit_f0(self, wav, tran, cluster_infer_ratio, speaker, f0_filter ,f0_predictor,cr_threshold=0.05):
207
+
208
+ f0_predictor_object = utils.get_f0_predictor(f0_predictor,hop_length=self.hop_size,sampling_rate=self.target_sample,device=self.dev,threshold=cr_threshold)
209
+
210
+ f0, uv = f0_predictor_object.compute_f0_uv(wav)
211
+ if f0_filter and sum(f0) == 0:
212
+ raise F0FilterException("No voice detected")
213
+ f0 = torch.FloatTensor(f0).to(self.dev)
214
+ uv = torch.FloatTensor(uv).to(self.dev)
215
+
216
+ f0 = f0 * 2 ** (tran / 12)
217
+ f0 = f0.unsqueeze(0)
218
+ uv = uv.unsqueeze(0)
219
+
220
+ wav16k = librosa.resample(wav, orig_sr=self.target_sample, target_sr=16000)
221
+ wav16k = torch.from_numpy(wav16k).to(self.dev)
222
+ c = self.hubert_model.encoder(wav16k)
223
+ c = utils.repeat_expand_2d(c.squeeze(0), f0.shape[1])
224
+
225
+ if cluster_infer_ratio !=0:
226
+ if self.feature_retrieval:
227
+ speaker_id = self.spk2id.get(speaker)
228
+ if speaker_id is None:
229
+ raise RuntimeError("The name you entered is not in the speaker list!")
230
+ if not speaker_id and type(speaker) is int:
231
+ if len(self.spk2id.__dict__) >= speaker:
232
+ speaker_id = speaker
233
+ feature_index = self.cluster_model[speaker_id]
234
+ feat_np = c.transpose(0,1).cpu().numpy()
235
+ if self.big_npy is not None or self.now_spk_id != speaker_id:
236
+ self.big_npy = feature_index.reconstruct_n(0, feature_index.ntotal)
237
+ self.now_spk_id = speaker_id
238
+ print("starting feature retrieval...")
239
+ score, ix = feature_index.search(feat_np, k=8)
240
+ weight = np.square(1 / score)
241
+ weight /= weight.sum(axis=1, keepdims=True)
242
+ npy = np.sum(self.big_npy[ix] * np.expand_dims(weight, axis=2), axis=1)
243
+ c = cluster_infer_ratio * npy + (1 - cluster_infer_ratio) * feat_np
244
+ c = torch.FloatTensor(c).to(self.dev).transpose(0,1)
245
+ print("end feature retrieval...")
246
+ else:
247
+ cluster_c = cluster.get_cluster_center_result(self.cluster_model, c.cpu().numpy().T, speaker).T
248
+ cluster_c = torch.FloatTensor(cluster_c).to(self.dev)
249
+ c = cluster_infer_ratio * cluster_c + (1 - cluster_infer_ratio) * c
250
+
251
+ c = c.unsqueeze(0)
252
+ return c, f0, uv
253
+
254
+ def infer(self, speaker, tran, raw_path,
255
+ cluster_infer_ratio=0,
256
+ auto_predict_f0=False,
257
+ noice_scale=0.4,
258
+ f0_filter=False,
259
+ f0_predictor='pm',
260
+ enhancer_adaptive_key = 0,
261
+ cr_threshold = 0.05,
262
+ k_step = 100,
263
+ frame = 0,
264
+ spk_mix = False,
265
+ second_encoding = False,
266
+ loudness_envelope_adjustment = 1
267
+ ):
268
+ wav, sr = librosa.load(raw_path, sr=self.target_sample)
269
+ if spk_mix:
270
+ c, f0, uv = self.get_unit_f0(wav, tran, 0, None, f0_filter,f0_predictor,cr_threshold=cr_threshold)
271
+ n_frames = f0.size(1)
272
+ sid = speaker[:, frame:frame+n_frames].transpose(0,1)
273
+ else:
274
+ speaker_id = self.spk2id.get(speaker)
275
+ if speaker_id is None:
276
+ raise RuntimeError("The name you entered is not in the speaker list!")
277
+ if not speaker_id and type(speaker) is int:
278
+ if len(self.spk2id.__dict__) >= speaker:
279
+ speaker_id = speaker
280
+ sid = torch.LongTensor([int(speaker_id)]).to(self.dev).unsqueeze(0)
281
+ c, f0, uv = self.get_unit_f0(wav, tran, cluster_infer_ratio, speaker, f0_filter,f0_predictor,cr_threshold=cr_threshold)
282
+ n_frames = f0.size(1)
283
+ if "half" in self.net_g_path and torch.cuda.is_available():
284
+ c = c.half()
285
+ with torch.no_grad():
286
+ start = time.time()
287
+ vol = None
288
+ if not self.only_diffusion:
289
+ vol = self.volume_extractor.extract(torch.FloatTensor(wav).to(self.dev)[None,:])[None,:].to(self.dev) if self.vol_embedding else None
290
+ audio,f0 = self.net_g_ms.infer(c, f0=f0, g=sid, uv=uv, predict_f0=auto_predict_f0, noice_scale=noice_scale,vol=vol)
291
+ audio = audio[0,0].data.float()
292
+ audio_mel = self.vocoder.extract(audio[None,:],self.target_sample) if self.shallow_diffusion else None
293
+ else:
294
+ audio = torch.FloatTensor(wav).to(self.dev)
295
+ audio_mel = None
296
+ if self.only_diffusion or self.shallow_diffusion:
297
+ vol = self.volume_extractor.extract(audio[None,:])[None,:,None].to(self.dev) if vol==None else vol[:,:,None]
298
+ if self.shallow_diffusion and second_encoding:
299
+ audio16k = librosa.resample(audio.detach().cpu().numpy(), orig_sr=self.target_sample, target_sr=16000)
300
+ audio16k = torch.from_numpy(audio16k).to(self.dev)
301
+ c = self.hubert_model.encoder(audio16k)
302
+ c = utils.repeat_expand_2d(c.squeeze(0), f0.shape[1])
303
+ f0 = f0[:,:,None]
304
+ c = c.transpose(-1,-2)
305
+ audio_mel = self.diffusion_model(
306
+ c,
307
+ f0,
308
+ vol,
309
+ spk_id = sid,
310
+ spk_mix_dict = None,
311
+ gt_spec=audio_mel,
312
+ infer=True,
313
+ infer_speedup=self.diffusion_args.infer.speedup,
314
+ method=self.diffusion_args.infer.method,
315
+ k_step=k_step)
316
+ audio = self.vocoder.infer(audio_mel, f0).squeeze()
317
+ if self.nsf_hifigan_enhance:
318
+ audio, _ = self.enhancer.enhance(
319
+ audio[None,:],
320
+ self.target_sample,
321
+ f0[:,:,None],
322
+ self.hps_ms.data.hop_length,
323
+ adaptive_key = enhancer_adaptive_key)
324
+ if loudness_envelope_adjustment != 1:
325
+ audio = utils.change_rms(wav,self.target_sample,audio,self.target_sample,loudness_envelope_adjustment)
326
+ use_time = time.time() - start
327
+ print("vits use time:{}".format(use_time))
328
+ return audio, audio.shape[-1], n_frames
329
+
330
+ def clear_empty(self):
331
+ # clean up vram
332
+ torch.cuda.empty_cache()
333
+
334
+ def unload_model(self):
335
+ # unload model
336
+ self.net_g_ms = self.net_g_ms.to("cpu")
337
+ del self.net_g_ms
338
+ if hasattr(self,"enhancer"):
339
+ self.enhancer.enhancer = self.enhancer.enhancer.to("cpu")
340
+ del self.enhancer.enhancer
341
+ del self.enhancer
342
+ gc.collect()
343
+
344
+ def slice_inference(self,
345
+ raw_audio_path,
346
+ spk,
347
+ tran,
348
+ slice_db,
349
+ cluster_infer_ratio,
350
+ auto_predict_f0,
351
+ noice_scale,
352
+ pad_seconds=0.5,
353
+ clip_seconds=0,
354
+ lg_num=0,
355
+ lgr_num =0.75,
356
+ f0_predictor='pm',
357
+ enhancer_adaptive_key = 0,
358
+ cr_threshold = 0.05,
359
+ k_step = 100,
360
+ use_spk_mix = False,
361
+ second_encoding = False,
362
+ loudness_envelope_adjustment = 1
363
+ ):
364
+ if use_spk_mix:
365
+ if len(self.spk2id) == 1:
366
+ spk = self.spk2id.keys()[0]
367
+ use_spk_mix = False
368
+ wav_path = Path(raw_audio_path).with_suffix('.wav')
369
+ chunks = slicer.cut(wav_path, db_thresh=slice_db)
370
+ audio_data, audio_sr = slicer.chunks2audio(wav_path, chunks)
371
+ per_size = int(clip_seconds*audio_sr)
372
+ lg_size = int(lg_num*audio_sr)
373
+ lg_size_r = int(lg_size*lgr_num)
374
+ lg_size_c_l = (lg_size-lg_size_r)//2
375
+ lg_size_c_r = lg_size-lg_size_r-lg_size_c_l
376
+ lg = np.linspace(0,1,lg_size_r) if lg_size!=0 else 0
377
+
378
+ if use_spk_mix:
379
+ assert len(self.spk2id) == len(spk)
380
+ audio_length = 0
381
+ for (slice_tag, data) in audio_data:
382
+ aud_length = int(np.ceil(len(data) / audio_sr * self.target_sample))
383
+ if slice_tag:
384
+ audio_length += aud_length // self.hop_size
385
+ continue
386
+ if per_size != 0:
387
+ datas = split_list_by_n(data, per_size,lg_size)
388
+ else:
389
+ datas = [data]
390
+ for k,dat in enumerate(datas):
391
+ pad_len = int(audio_sr * pad_seconds)
392
+ per_length = int(np.ceil(len(dat) / audio_sr * self.target_sample))
393
+ a_length = per_length + 2 * pad_len
394
+ audio_length += a_length // self.hop_size
395
+ audio_length += len(audio_data)
396
+ spk_mix_tensor = torch.zeros(size=(len(spk), audio_length)).to(self.dev)
397
+ for i in range(len(spk)):
398
+ last_end = None
399
+ for mix in spk[i]:
400
+ if mix[3]<0. or mix[2]<0.:
401
+ raise RuntimeError("mix value must higer Than zero!")
402
+ begin = int(audio_length * mix[0])
403
+ end = int(audio_length * mix[1])
404
+ length = end - begin
405
+ if length<=0:
406
+ raise RuntimeError("begin Must lower Than end!")
407
+ step = (mix[3] - mix[2])/length
408
+ if last_end is not None:
409
+ if last_end != begin:
410
+ raise RuntimeError("[i]EndTime Must Equal [i+1]BeginTime!")
411
+ last_end = end
412
+ if step == 0.:
413
+ spk_mix_data = torch.zeros(length).to(self.dev) + mix[2]
414
+ else:
415
+ spk_mix_data = torch.arange(mix[2],mix[3],step).to(self.dev)
416
+ if(len(spk_mix_data)<length):
417
+ num_pad = length - len(spk_mix_data)
418
+ spk_mix_data = torch.nn.functional.pad(spk_mix_data, [0, num_pad], mode="reflect").to(self.dev)
419
+ spk_mix_tensor[i][begin:end] = spk_mix_data[:length]
420
+
421
+ spk_mix_ten = torch.sum(spk_mix_tensor,dim=0).unsqueeze(0).to(self.dev)
422
+ # spk_mix_tensor[0][spk_mix_ten<0.001] = 1.0
423
+ for i, x in enumerate(spk_mix_ten[0]):
424
+ if x == 0.0:
425
+ spk_mix_ten[0][i] = 1.0
426
+ spk_mix_tensor[:,i] = 1.0 / len(spk)
427
+ spk_mix_tensor = spk_mix_tensor / spk_mix_ten
428
+ if not ((torch.sum(spk_mix_tensor,dim=0) - 1.)<0.0001).all():
429
+ raise RuntimeError("sum(spk_mix_tensor) not equal 1")
430
+ spk = spk_mix_tensor
431
+
432
+ global_frame = 0
433
+ audio = []
434
+ for (slice_tag, data) in audio_data:
435
+ print(f'#=====segment start, {round(len(data) / audio_sr, 3)}s======')
436
+ # padd
437
+ length = int(np.ceil(len(data) / audio_sr * self.target_sample))
438
+ if slice_tag:
439
+ print('jump empty segment')
440
+ _audio = np.zeros(length)
441
+ audio.extend(list(pad_array(_audio, length)))
442
+ global_frame += length // self.hop_size
443
+ continue
444
+ if per_size != 0:
445
+ datas = split_list_by_n(data, per_size,lg_size)
446
+ else:
447
+ datas = [data]
448
+ for k,dat in enumerate(datas):
449
+ per_length = int(np.ceil(len(dat) / audio_sr * self.target_sample)) if clip_seconds!=0 else length
450
+ if clip_seconds!=0: print(f'###=====segment clip start, {round(len(dat) / audio_sr, 3)}s======')
451
+ # padd
452
+ pad_len = int(audio_sr * pad_seconds)
453
+ dat = np.concatenate([np.zeros([pad_len]), dat, np.zeros([pad_len])])
454
+ raw_path = io.BytesIO()
455
+ soundfile.write(raw_path, dat, audio_sr, format="wav")
456
+ raw_path.seek(0)
457
+ out_audio, out_sr, out_frame = self.infer(spk, tran, raw_path,
458
+ cluster_infer_ratio=cluster_infer_ratio,
459
+ auto_predict_f0=auto_predict_f0,
460
+ noice_scale=noice_scale,
461
+ f0_predictor = f0_predictor,
462
+ enhancer_adaptive_key = enhancer_adaptive_key,
463
+ cr_threshold = cr_threshold,
464
+ k_step = k_step,
465
+ frame = global_frame,
466
+ spk_mix = use_spk_mix,
467
+ second_encoding = second_encoding,
468
+ loudness_envelope_adjustment = loudness_envelope_adjustment
469
+ )
470
+ global_frame += out_frame
471
+ _audio = out_audio.cpu().numpy()
472
+ pad_len = int(self.target_sample * pad_seconds)
473
+ _audio = _audio[pad_len:-pad_len]
474
+ _audio = pad_array(_audio, per_length)
475
+ if lg_size!=0 and k!=0:
476
+ lg1 = audio[-(lg_size_r+lg_size_c_r):-lg_size_c_r] if lgr_num != 1 else audio[-lg_size:]
477
+ lg2 = _audio[lg_size_c_l:lg_size_c_l+lg_size_r] if lgr_num != 1 else _audio[0:lg_size]
478
+ lg_pre = lg1*(1-lg)+lg2*lg
479
+ audio = audio[0:-(lg_size_r+lg_size_c_r)] if lgr_num != 1 else audio[0:-lg_size]
480
+ audio.extend(lg_pre)
481
+ _audio = _audio[lg_size_c_l+lg_size_r:] if lgr_num != 1 else _audio[lg_size:]
482
+ audio.extend(list(_audio))
483
+ return np.array(audio)
484
+
485
+ class RealTimeVC:
486
+ def __init__(self):
487
+ self.last_chunk = None
488
+ self.last_o = None
489
+ self.chunk_len = 16000 # chunk length
490
+ self.pre_len = 3840 # cross fade length, multiples of 640
491
+
492
+ # Input and output are 1-dimensional numpy waveform arrays
493
+
494
+ def process(self, svc_model, speaker_id, f_pitch_change, input_wav_path,
495
+ cluster_infer_ratio=0,
496
+ auto_predict_f0=False,
497
+ noice_scale=0.4,
498
+ f0_filter=False):
499
+
500
+ import maad
501
+ audio, sr = torchaudio.load(input_wav_path)
502
+ audio = audio.cpu().numpy()[0]
503
+ temp_wav = io.BytesIO()
504
+ if self.last_chunk is None:
505
+ input_wav_path.seek(0)
506
+
507
+ audio, sr = svc_model.infer(speaker_id, f_pitch_change, input_wav_path,
508
+ cluster_infer_ratio=cluster_infer_ratio,
509
+ auto_predict_f0=auto_predict_f0,
510
+ noice_scale=noice_scale,
511
+ f0_filter=f0_filter)
512
+
513
+ audio = audio.cpu().numpy()
514
+ self.last_chunk = audio[-self.pre_len:]
515
+ self.last_o = audio
516
+ return audio[-self.chunk_len:]
517
+ else:
518
+ audio = np.concatenate([self.last_chunk, audio])
519
+ soundfile.write(temp_wav, audio, sr, format="wav")
520
+ temp_wav.seek(0)
521
+
522
+ audio, sr = svc_model.infer(speaker_id, f_pitch_change, temp_wav,
523
+ cluster_infer_ratio=cluster_infer_ratio,
524
+ auto_predict_f0=auto_predict_f0,
525
+ noice_scale=noice_scale,
526
+ f0_filter=f0_filter)
527
+
528
+ audio = audio.cpu().numpy()
529
+ ret = maad.util.crossfade(self.last_o, audio, self.pre_len)
530
+ self.last_chunk = audio[-self.pre_len:]
531
+ self.last_o = audio
532
+ return ret[self.chunk_len:2 * self.chunk_len]
533
+