From 67e94925d18ef91f5ad99fff18bd9e777ae4162a Mon Sep 17 00:00:00 2001 From: 34j <55338215+34j@users.noreply.github.com> Date: Fri, 31 Mar 2023 19:43:37 +0900 Subject: [PATCH 01/47] feat: add `half` options --- src/so_vits_svc_fork/inference/infer_tool.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/so_vits_svc_fork/inference/infer_tool.py b/src/so_vits_svc_fork/inference/infer_tool.py index 5604192f..9a2e1c09 100644 --- a/src/so_vits_svc_fork/inference/infer_tool.py +++ b/src/so_vits_svc_fork/inference/infer_tool.py @@ -94,6 +94,7 @@ def __init__( config_path: str, device: torch.device | str | None = None, cluster_model_path: Path | str | None = None, + half: bool = True, ): self.net_g_path = net_g_path if device is None: @@ -106,6 +107,7 @@ def __init__( self.hop_size = self.hps_ms.data.hop_length self.spk2id = self.hps_ms.spk self.hubert_model = utils.get_hubert_model().to(self.dev) + self.half = half self.load_model() if cluster_model_path is not None and Path(cluster_model_path).exists(): self.cluster_model = cluster.get_cluster_model(cluster_model_path) @@ -117,7 +119,7 @@ def load_model(self): **self.hps_ms.model, ) _ = utils.load_checkpoint(self.net_g_path, self.net_g_ms, None) - if "half" in self.net_g_path and torch.cuda.is_available(): + if self.half: _ = self.net_g_ms.half().eval().to(self.dev) else: _ = self.net_g_ms.eval().to(self.dev) @@ -205,8 +207,10 @@ def infer( c, f0, uv = self.get_unit_f0( audio, transpose, cluster_infer_ratio, speaker, f0_method ) - if "half" in self.net_g_path and torch.cuda.is_available(): + if self.half: c = c.half() + f0 = f0.half() + uv = uv.half() # inference with torch.no_grad(): From 9a6de1f8094ca294e9bb1c9851e92de65a10591c Mon Sep 17 00:00:00 2001 From: 34j <55338215+34j@users.noreply.github.com> Date: Fri, 31 Mar 2023 19:44:21 +0900 Subject: [PATCH 02/47] fix(hifigan): fix dtype for n --- src/so_vits_svc_fork/vdecoder/hifigan/models.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/so_vits_svc_fork/vdecoder/hifigan/models.py b/src/so_vits_svc_fork/vdecoder/hifigan/models.py index 1c83dea9..7b84f9c3 100644 --- a/src/so_vits_svc_fork/vdecoder/hifigan/models.py +++ b/src/so_vits_svc_fork/vdecoder/hifigan/models.py @@ -286,8 +286,11 @@ def forward(self, f0): with torch.no_grad(): # f0_buf = torch.zeros(f0.shape[0], f0.shape[1], self.dim, device=f0.device) # fundamental component + # fn = torch.multiply( + # f0, torch.FloatTensor([[range(1, self.harmonic_num + 2)]]).to(f0.device) + # ) fn = torch.multiply( - f0, torch.FloatTensor([[range(1, self.harmonic_num + 2)]]).to(f0.device) + f0, torch.arange(1, self.harmonic_num + 2).to(f0.device).to(f0.dtype) ) # generate sine waveforms From 59dedf1981e0db8961342c7642308c8f0eec25be Mon Sep 17 00:00:00 2001 From: 34j <55338215+34j@users.noreply.github.com> Date: Fri, 31 Mar 2023 20:04:38 +0900 Subject: [PATCH 03/47] fix: remove unused files --- src/so_vits_svc_fork/vdecoder/hifigan/env.py | 15 -- .../vdecoder/hifigan/models.py | 56 ------ .../vdecoder/hifigan/nvSTFT.py | 162 ------------------ 3 files changed, 233 deletions(-) delete mode 100644 src/so_vits_svc_fork/vdecoder/hifigan/env.py delete mode 100644 src/so_vits_svc_fork/vdecoder/hifigan/nvSTFT.py diff --git a/src/so_vits_svc_fork/vdecoder/hifigan/env.py b/src/so_vits_svc_fork/vdecoder/hifigan/env.py deleted file mode 100644 index a1231a2d..00000000 --- a/src/so_vits_svc_fork/vdecoder/hifigan/env.py +++ /dev/null @@ -1,15 +0,0 @@ -import os -import shutil - - -class AttrDict(dict): - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - self.__dict__ = self - - -def build_env(config, config_name, path): - t_path = os.path.join(path, config_name) - if config != t_path: - os.makedirs(path, exist_ok=True) - shutil.copyfile(config, os.path.join(path, config_name)) diff --git a/src/so_vits_svc_fork/vdecoder/hifigan/models.py b/src/so_vits_svc_fork/vdecoder/hifigan/models.py index 7b84f9c3..779f4ec6 100644 --- a/src/so_vits_svc_fork/vdecoder/hifigan/models.py +++ b/src/so_vits_svc_fork/vdecoder/hifigan/models.py @@ -1,5 +1,3 @@ -import json -import os from logging import getLogger import numpy as np @@ -9,7 +7,6 @@ from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn.utils import remove_weight_norm, spectral_norm, weight_norm -from .env import AttrDict from .utils import get_padding, init_weights LOG = getLogger(__name__) @@ -17,25 +14,6 @@ LRELU_SLOPE = 0.1 -def load_model(model_path, device="cuda"): - config_file = os.path.join(os.path.split(model_path)[0], "config.json") - with open(config_file) as f: - data = f.read() - - global h - json_config = json.loads(data) - h = AttrDict(json_config) - - generator = Generator(h).to(device) - - cp_dict = torch.load(model_path) - generator.load_state_dict(cp_dict["generator"]) - generator.eval() - generator.remove_weight_norm() - del cp_dict - return generator, h - - class ResBlock1(torch.nn.Module): def __init__(self, h, channels, kernel_size=3, dilation=(1, 3, 5)): super().__init__() @@ -621,37 +599,3 @@ def forward(self, y, y_hat): fmap_gs.append(fmap_g) return y_d_rs, y_d_gs, fmap_rs, fmap_gs - - -def feature_loss(fmap_r, fmap_g): - loss = 0 - for dr, dg in zip(fmap_r, fmap_g): - for rl, gl in zip(dr, dg): - loss += torch.mean(torch.abs(rl - gl)) - - return loss * 2 - - -def discriminator_loss(disc_real_outputs, disc_generated_outputs): - loss = 0 - r_losses = [] - g_losses = [] - for dr, dg in zip(disc_real_outputs, disc_generated_outputs): - r_loss = torch.mean((1 - dr) ** 2) - g_loss = torch.mean(dg**2) - loss += r_loss + g_loss - r_losses.append(r_loss.item()) - g_losses.append(g_loss.item()) - - return loss, r_losses, g_losses - - -def generator_loss(disc_outputs): - loss = 0 - gen_losses = [] - for dg in disc_outputs: - l = torch.mean((1 - dg) ** 2) - gen_losses.append(l) - loss += l - - return loss, gen_losses diff --git a/src/so_vits_svc_fork/vdecoder/hifigan/nvSTFT.py b/src/so_vits_svc_fork/vdecoder/hifigan/nvSTFT.py deleted file mode 100644 index a33805d6..00000000 --- a/src/so_vits_svc_fork/vdecoder/hifigan/nvSTFT.py +++ /dev/null @@ -1,162 +0,0 @@ -import os - -os.environ["LRU_CACHE_CAPACITY"] = "3" -from logging import getLogger - -import librosa -import numpy as np -import soundfile as sf -import torch -import torch.utils.data -from librosa.filters import mel as librosa_mel_fn - -LOG = getLogger(__name__) - - -def load_wav_to_torch(full_path, target_sr=None, return_empty_on_exception=False): - sampling_rate = None - try: - data, sampling_rate = sf.read(full_path, always_2d=True) # than soundfile. - except Exception as ex: - LOG.info(f"'{full_path}' failed to load.\nException:") - LOG.info(ex) - if return_empty_on_exception: - return [], sampling_rate or target_sr or 32000 - else: - raise Exception(ex) - - if len(data.shape) > 1: - data = data[:, 0] - assert ( - len(data) > 2 - ) # check duration of audio file is > 2 samples (because otherwise the slice operation was on the wrong dimension) - - if np.issubdtype(data.dtype, np.integer): # if audio data is type int - max_mag = -np.iinfo( - data.dtype - ).min # maximum magnitude = min possible value of intXX - else: # if audio data is type fp32 - max_mag = max(np.amax(data), -np.amin(data)) - max_mag = ( - (2**31) + 1 - if max_mag > (2**15) - else ((2**15) + 1 if max_mag > 1.01 else 1.0) - ) # data should be either 16-bit INT, 32-bit INT or [-1 to 1] float32 - - data = torch.FloatTensor(data.astype(np.float32)) / max_mag - - if ( - torch.isinf(data) | torch.isnan(data) - ).any() and return_empty_on_exception: # resample will crash with inf/NaN inputs. return_empty_on_exception will return empty arr instead of except - return [], sampling_rate or target_sr or 32000 - if target_sr is not None and sampling_rate != target_sr: - data = torch.from_numpy( - librosa.core.resample( - data.numpy(), orig_sr=sampling_rate, target_sr=target_sr - ) - ) - sampling_rate = target_sr - - return data, sampling_rate - - -def dynamic_range_compression(x, C=1, clip_val=1e-5): - return np.log(np.clip(x, a_min=clip_val, a_max=None) * C) - - -def dynamic_range_decompression(x, C=1): - return np.exp(x) / C - - -def dynamic_range_compression_torch(x, C=1, clip_val=1e-5): - return torch.log(torch.clamp(x, min=clip_val) * C) - - -def dynamic_range_decompression_torch(x, C=1): - return torch.exp(x) / C - - -class STFT: - def __init__( - self, - sr=22050, - n_mels=80, - n_fft=1024, - win_size=1024, - hop_length=256, - fmin=20, - fmax=11025, - clip_val=1e-5, - ): - self.target_sr = sr - - self.n_mels = n_mels - self.n_fft = n_fft - self.win_size = win_size - self.hop_length = hop_length - self.fmin = fmin - self.fmax = fmax - self.clip_val = clip_val - self.mel_basis = {} - self.hann_window = {} - - def get_mel(self, y, center=False): - sampling_rate = self.target_sr - n_mels = self.n_mels - n_fft = self.n_fft - win_size = self.win_size - hop_length = self.hop_length - fmin = self.fmin - fmax = self.fmax - clip_val = self.clip_val - - if torch.min(y) < -1.0: - LOG.info("min value is ", torch.min(y)) - if torch.max(y) > 1.0: - LOG.info("max value is ", torch.max(y)) - - if fmax not in self.mel_basis: - mel = librosa_mel_fn( - sr=sampling_rate, n_fft=n_fft, n_mels=n_mels, fmin=fmin, fmax=fmax - ) - self.mel_basis[str(fmax) + "_" + str(y.device)] = ( - torch.from_numpy(mel).float().to(y.device) - ) - self.hann_window[str(y.device)] = torch.hann_window(self.win_size).to( - y.device - ) - - y = torch.nn.functional.pad( - y.unsqueeze(1), - (int((n_fft - hop_length) / 2), int((n_fft - hop_length) / 2)), - mode="reflect", - ) - y = y.squeeze(1) - - spec = torch.stft( - y, - n_fft, - hop_length=hop_length, - win_length=win_size, - window=self.hann_window[str(y.device)], - center=center, - pad_mode="reflect", - normalized=False, - onesided=True, - ) - # LOG.info(111,spec) - spec = torch.sqrt(spec.pow(2).sum(-1) + (1e-9)) - # LOG.info(222,spec) - spec = torch.matmul(self.mel_basis[str(fmax) + "_" + str(y.device)], spec) - # LOG.info(333,spec) - spec = dynamic_range_compression_torch(spec, clip_val=clip_val) - # LOG.info(444,spec) - return spec - - def __call__(self, audiopath): - audio, sr = load_wav_to_torch(audiopath, target_sr=self.target_sr) - spect = self.get_mel(audio.unsqueeze(0)).squeeze(0) - return spect - - -stft = STFT() From 87fd22b12b0c415a48cc71b539ded61a83779f96 Mon Sep 17 00:00:00 2001 From: 34j <55338215+34j@users.noreply.github.com> Date: Fri, 31 Mar 2023 20:42:06 +0900 Subject: [PATCH 04/47] feat: mb-istft-vits prototype --- .idea/workspace.xml | 52 +-- LICENSE | 201 ++++++++++ src/so_vits_svc_fork/models.py | 51 ++- src/so_vits_svc_fork/train.py | 27 +- .../vdecoder/mb_istft/__init__.py | 0 .../vdecoder/mb_istft/generators.py | 374 ++++++++++++++++++ .../vdecoder/mb_istft/loss.py | 11 + .../vdecoder/mb_istft/pqmf.py | 130 ++++++ .../vdecoder/mb_istft/stft.py | 248 ++++++++++++ .../vdecoder/mb_istft/stft_loss.py | 140 +++++++ 10 files changed, 1177 insertions(+), 57 deletions(-) create mode 100644 src/so_vits_svc_fork/vdecoder/mb_istft/__init__.py create mode 100644 src/so_vits_svc_fork/vdecoder/mb_istft/generators.py create mode 100644 src/so_vits_svc_fork/vdecoder/mb_istft/loss.py create mode 100644 src/so_vits_svc_fork/vdecoder/mb_istft/pqmf.py create mode 100644 src/so_vits_svc_fork/vdecoder/mb_istft/stft.py create mode 100644 src/so_vits_svc_fork/vdecoder/mb_istft/stft_loss.py diff --git a/.idea/workspace.xml b/.idea/workspace.xml index 7b269da5..4c57db80 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -2,56 +2,10 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + - - + diff --git a/LICENSE b/LICENSE index 764c22e5..0bcb3ed1 100644 --- a/LICENSE +++ b/LICENSE @@ -20,3 +20,204 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/src/so_vits_svc_fork/models.py b/src/so_vits_svc_fork/models.py index 2dc3db7c..fd2da327 100644 --- a/src/so_vits_svc_fork/models.py +++ b/src/so_vits_svc_fork/models.py @@ -1,3 +1,6 @@ +from logging import getLogger +from typing import Literal + import torch from torch import nn from torch.nn import Conv1d, Conv2d @@ -13,6 +16,8 @@ from .utils import f0_to_coarse from .vdecoder.hifigan.models import Generator +LOG = getLogger(__name__) + class ResidualCouplingBlock(nn.Module): def __init__( @@ -392,7 +397,11 @@ def __init__( ssl_dim, n_speakers, sampling_rate=44100, - **kwargs + type_: Literal["hifi-gan", "istft", "ms-istft", "mb-istft"] = "hifi-gan", + gen_istft_n_fft: int = 16, + gen_istft_hop_size: int = 4, + subbands: bool = False, + **kwargs, ): super().__init__() self.spec_channels = spec_channels @@ -436,7 +445,29 @@ def __init__( "upsample_kernel_sizes": upsample_kernel_sizes, "gin_channels": gin_channels, } - self.dec = Generator(h=hps) + + LOG.info(f"Decoder type: {type_}") + if type_ == "hifi-gan": + self.dec = Generator(h=hps) + self.mb = False + else: + from .vdecoder.mb_istft.generators import ( + Multiband_iSTFT_Generator, + Multistream_iSTFT_Generator, + iSTFT_Generator, + ) + + # gen_istft_n_fft, gen_istft_hop_size, subbands + if type_ == "istft": + self.dec = iSTFT_Generator(**hps) + elif type_ == "ms-istft": + self.dec = Multistream_iSTFT_Generator(**hps) + elif type_ == "mb-istft": + self.dec = Multiband_iSTFT_Generator(**hps) + else: + raise ValueError(f"Unknown type: {type_}") + self.mb = True + self.enc_q = Encoder( spec_channels, inter_channels, @@ -485,10 +516,15 @@ def forward(self, c, f0, uv, spec, g=None, c_lengths=None, spec_lengths=None): ) # nsf decoder - o = self.dec(z_slice, g=g, f0=pitch_slice) - + # MB-iSTFT-VITS + if self.dec: + o, o_mb = self.dec(z_slice, g=g) + else: + o = self.dec(z_slice, g=g, f0=pitch_slice) + o_mb = None return ( o, + o_mb, ids_slice, spec_mask, (z, z_p, m_p, logs_p, m_q, logs_q), @@ -515,5 +551,10 @@ def infer(self, c, f0, uv, g=None, noice_scale=0.35, predict_f0=False): x, x_mask, f0=f0_to_coarse(f0), noice_scale=noice_scale ) z = self.flow(z_p, c_mask, g=g, reverse=True) - o = self.dec(z * c_mask, g=g, f0=f0) + + # MB-iSTFT-VITS + if self.mb: + o, o_mb = self.dec(z * c_mask, g=g) + else: + o = self.dec(z * c_mask, g=g, f0=f0) return o diff --git a/src/so_vits_svc_fork/train.py b/src/so_vits_svc_fork/train.py index ec09859c..515d0ebc 100644 --- a/src/so_vits_svc_fork/train.py +++ b/src/so_vits_svc_fork/train.py @@ -267,6 +267,17 @@ def train_and_evaluate( loss_gen, losses_gen = generator_loss(y_d_hat_g) loss_lf0 = F.mse_loss(pred_lf0, lf0) loss_gen_all = loss_gen + loss_fm + loss_mel + loss_kl + loss_lf0 + + # MB-iSTFT-VITS + loss_subband = torch.tensor(0.0) + if hps.model.__dict__.get("type_") == "mb-istft-vits": + from .vdecoder.mb_istft.loss import subband_stft_loss + from .vdecoder.mb_istft.pqmf import PQMF + + y_mb = PQMF(y.device).analysis(y) + loss_subband = subband_stft_loss(hps, y_mb, y_hat) + loss_gen_all += loss_subband + optim_g.zero_grad() scaler.scale(loss_gen_all).backward() scaler.unscale_(optim_g) @@ -277,15 +288,21 @@ def train_and_evaluate( if rank == 0: if global_step % hps.train.log_interval == 0: lr = optim_g.param_groups[0]["lr"] - losses = [loss_disc, loss_gen, loss_fm, loss_mel, loss_kl] + losses = { + "discriminator": loss_disc.item(), + "generator": loss_gen.item(), + "feature_matching": loss_fm.item(), + "melspectrogram": loss_mel.item(), + "kl_divergence": loss_kl.item(), + } + if hps.model.__dict__.get("type_") == "mb-istft-vits": + losses["subband_stft"] = loss_subband.item() LOG.info( "Train Epoch: {} [{:.0f}%]".format( epoch, 100.0 * batch_idx / len(train_loader) ) ) - LOG.info( - f"Losses: {[x.item() for x in losses]}, step: {global_step}, lr: {lr}" - ) + LOG.info(f"Losses: {losses}, step: {global_step}, lr: {lr}") scalar_dict = { "loss/g/total": loss_gen_all, @@ -300,6 +317,8 @@ def train_and_evaluate( "loss/g/mel": loss_mel, "loss/g/kl": loss_kl, "loss/g/lf0": loss_lf0, + # MB-iSTFT-VITS + "loss/g/subband": loss_subband, } ) diff --git a/src/so_vits_svc_fork/vdecoder/mb_istft/__init__.py b/src/so_vits_svc_fork/vdecoder/mb_istft/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/src/so_vits_svc_fork/vdecoder/mb_istft/generators.py b/src/so_vits_svc_fork/vdecoder/mb_istft/generators.py new file mode 100644 index 00000000..c5e469a4 --- /dev/null +++ b/src/so_vits_svc_fork/vdecoder/mb_istft/generators.py @@ -0,0 +1,374 @@ +import math + +import torch +from torch import nn +from torch.nn import Conv1d, ConvTranspose1d +from torch.nn import functional as F +from torch.nn.utils import remove_weight_norm, weight_norm + +from ...modules import modules +from ...modules.commons import get_padding, init_weights +from .pqmf import PQMF +from .stft import TorchSTFT + + +class iSTFT_Generator(torch.nn.Module): + def __init__( + self, + initial_channel, + resblock, + resblock_kernel_sizes, + resblock_dilation_sizes, + upsample_rates, + upsample_initial_channel, + upsample_kernel_sizes, + gen_istft_n_fft, + gen_istft_hop_size, + gin_channels=0, + ): + super().__init__() + # self.h = h + self.gen_istft_n_fft = gen_istft_n_fft + self.gen_istft_hop_size = gen_istft_hop_size + + self.num_kernels = len(resblock_kernel_sizes) + self.num_upsamples = len(upsample_rates) + self.conv_pre = weight_norm( + Conv1d(initial_channel, upsample_initial_channel, 7, 1, padding=3) + ) + resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2 + + self.ups = nn.ModuleList() + for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)): + self.ups.append( + weight_norm( + ConvTranspose1d( + upsample_initial_channel // (2**i), + upsample_initial_channel // (2 ** (i + 1)), + k, + u, + padding=(k - u) // 2, + ) + ) + ) + + self.resblocks = nn.ModuleList() + for i in range(len(self.ups)): + ch = upsample_initial_channel // (2 ** (i + 1)) + for j, (k, d) in enumerate( + zip(resblock_kernel_sizes, resblock_dilation_sizes) + ): + self.resblocks.append(resblock(ch, k, d)) + + self.post_n_fft = self.gen_istft_n_fft + self.conv_post = weight_norm(Conv1d(ch, self.post_n_fft + 2, 7, 1, padding=3)) + self.ups.apply(init_weights) + self.conv_post.apply(init_weights) + self.reflection_pad = torch.nn.ReflectionPad1d((1, 0)) + self.stft = TorchSTFT( + filter_length=self.gen_istft_n_fft, + hop_length=self.gen_istft_hop_size, + win_length=self.gen_istft_n_fft, + ) + + def forward(self, x, g=None): + x = self.conv_pre(x) + for i in range(self.num_upsamples): + x = F.leaky_relu(x, modules.LRELU_SLOPE) + x = self.ups[i](x) + xs = None + for j in range(self.num_kernels): + if xs is None: + xs = self.resblocks[i * self.num_kernels + j](x) + else: + xs += self.resblocks[i * self.num_kernels + j](x) + x = xs / self.num_kernels + x = F.leaky_relu(x) + x = self.reflection_pad(x) + x = self.conv_post(x) + spec = torch.exp(x[:, : self.post_n_fft // 2 + 1, :]) + phase = math.pi * torch.sin(x[:, self.post_n_fft // 2 + 1 :, :]) + out = self.stft.inverse(spec, phase).to(x.device) + return out, None + + def remove_weight_norm(self): + print("Removing weight norm...") + for l in self.ups: + remove_weight_norm(l) + for l in self.resblocks: + l.remove_weight_norm() + remove_weight_norm(self.conv_pre) + remove_weight_norm(self.conv_post) + + +class Multiband_iSTFT_Generator(torch.nn.Module): + def __init__( + self, + initial_channel, + resblock, + resblock_kernel_sizes, + resblock_dilation_sizes, + upsample_rates, + upsample_initial_channel, + upsample_kernel_sizes, + gen_istft_n_fft, + gen_istft_hop_size, + subbands, + gin_channels=0, + ): + super().__init__() + # self.h = h + self.subbands = subbands + self.num_kernels = len(resblock_kernel_sizes) + self.num_upsamples = len(upsample_rates) + self.conv_pre = weight_norm( + Conv1d(initial_channel, upsample_initial_channel, 7, 1, padding=3) + ) + resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2 + + self.ups = nn.ModuleList() + for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)): + self.ups.append( + weight_norm( + ConvTranspose1d( + upsample_initial_channel // (2**i), + upsample_initial_channel // (2 ** (i + 1)), + k, + u, + padding=(k - u) // 2, + ) + ) + ) + + self.resblocks = nn.ModuleList() + for i in range(len(self.ups)): + ch = upsample_initial_channel // (2 ** (i + 1)) + for j, (k, d) in enumerate( + zip(resblock_kernel_sizes, resblock_dilation_sizes) + ): + self.resblocks.append(resblock(ch, k, d)) + + self.post_n_fft = gen_istft_n_fft + self.ups.apply(init_weights) + self.reflection_pad = torch.nn.ReflectionPad1d((1, 0)) + self.reshape_pixelshuffle = [] + + self.subband_conv_post = weight_norm( + Conv1d(ch, self.subbands * (self.post_n_fft + 2), 7, 1, padding=3) + ) + + self.subband_conv_post.apply(init_weights) + + self.gen_istft_n_fft = gen_istft_n_fft + self.gen_istft_hop_size = gen_istft_hop_size + + def forward(self, x, g=None): + stft = TorchSTFT( + filter_length=self.gen_istft_n_fft, + hop_length=self.gen_istft_hop_size, + win_length=self.gen_istft_n_fft, + ).to(x.device) + pqmf = PQMF(x.device) + + x = self.conv_pre(x) # [B, ch, length] + + for i in range(self.num_upsamples): + x = F.leaky_relu(x, modules.LRELU_SLOPE) + x = self.ups[i](x) + + xs = None + for j in range(self.num_kernels): + if xs is None: + xs = self.resblocks[i * self.num_kernels + j](x) + else: + xs += self.resblocks[i * self.num_kernels + j](x) + x = xs / self.num_kernels + + x = F.leaky_relu(x) + x = self.reflection_pad(x) + x = self.subband_conv_post(x) + x = torch.reshape( + x, (x.shape[0], self.subbands, x.shape[1] // self.subbands, x.shape[-1]) + ) + + spec = torch.exp(x[:, :, : self.post_n_fft // 2 + 1, :]) + phase = math.pi * torch.sin(x[:, :, self.post_n_fft // 2 + 1 :, :]) + + y_mb_hat = stft.inverse( + torch.reshape( + spec, + ( + spec.shape[0] * self.subbands, + self.gen_istft_n_fft // 2 + 1, + spec.shape[-1], + ), + ), + torch.reshape( + phase, + ( + phase.shape[0] * self.subbands, + self.gen_istft_n_fft // 2 + 1, + phase.shape[-1], + ), + ), + ) + y_mb_hat = torch.reshape( + y_mb_hat, (x.shape[0], self.subbands, 1, y_mb_hat.shape[-1]) + ) + y_mb_hat = y_mb_hat.squeeze(-2) + + y_g_hat = pqmf.synthesis(y_mb_hat) + + return y_g_hat, y_mb_hat + + def remove_weight_norm(self): + print("Removing weight norm...") + for l in self.ups: + remove_weight_norm(l) + for l in self.resblocks: + l.remove_weight_norm() + + +class Multistream_iSTFT_Generator(torch.nn.Module): + def __init__( + self, + initial_channel, + resblock, + resblock_kernel_sizes, + resblock_dilation_sizes, + upsample_rates, + upsample_initial_channel, + upsample_kernel_sizes, + gen_istft_n_fft, + gen_istft_hop_size, + subbands, + gin_channels=0, + ): + super().__init__() + # self.h = h + self.subbands = subbands + self.num_kernels = len(resblock_kernel_sizes) + self.num_upsamples = len(upsample_rates) + self.conv_pre = weight_norm( + Conv1d(initial_channel, upsample_initial_channel, 7, 1, padding=3) + ) + resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2 + + self.ups = nn.ModuleList() + for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)): + self.ups.append( + weight_norm( + ConvTranspose1d( + upsample_initial_channel // (2**i), + upsample_initial_channel // (2 ** (i + 1)), + k, + u, + padding=(k - u) // 2, + ) + ) + ) + + self.resblocks = nn.ModuleList() + for i in range(len(self.ups)): + ch = upsample_initial_channel // (2 ** (i + 1)) + for j, (k, d) in enumerate( + zip(resblock_kernel_sizes, resblock_dilation_sizes) + ): + self.resblocks.append(resblock(ch, k, d)) + + self.post_n_fft = gen_istft_n_fft + self.ups.apply(init_weights) + self.reflection_pad = torch.nn.ReflectionPad1d((1, 0)) + self.reshape_pixelshuffle = [] + + self.subband_conv_post = weight_norm( + Conv1d(ch, self.subbands * (self.post_n_fft + 2), 7, 1, padding=3) + ) + + self.subband_conv_post.apply(init_weights) + + self.gen_istft_n_fft = gen_istft_n_fft + self.gen_istft_hop_size = gen_istft_hop_size + + updown_filter = torch.zeros( + (self.subbands, self.subbands, self.subbands) + ).float() + for k in range(self.subbands): + updown_filter[k, k, 0] = 1.0 + self.register_buffer("updown_filter", updown_filter) + self.multistream_conv_post = weight_norm( + Conv1d(4, 1, kernel_size=63, bias=False, padding=get_padding(63, 1)) + ) + self.multistream_conv_post.apply(init_weights) + + def forward(self, x, g=None): + stft = TorchSTFT( + filter_length=self.gen_istft_n_fft, + hop_length=self.gen_istft_hop_size, + win_length=self.gen_istft_n_fft, + ).to(x.device) + # pqmf = PQMF(x.device) + + x = self.conv_pre(x) # [B, ch, length] + + for i in range(self.num_upsamples): + x = F.leaky_relu(x, modules.LRELU_SLOPE) + x = self.ups[i](x) + + xs = None + for j in range(self.num_kernels): + if xs is None: + xs = self.resblocks[i * self.num_kernels + j](x) + else: + xs += self.resblocks[i * self.num_kernels + j](x) + x = xs / self.num_kernels + + x = F.leaky_relu(x) + x = self.reflection_pad(x) + x = self.subband_conv_post(x) + x = torch.reshape( + x, (x.shape[0], self.subbands, x.shape[1] // self.subbands, x.shape[-1]) + ) + + spec = torch.exp(x[:, :, : self.post_n_fft // 2 + 1, :]) + phase = math.pi * torch.sin(x[:, :, self.post_n_fft // 2 + 1 :, :]) + + y_mb_hat = stft.inverse( + torch.reshape( + spec, + ( + spec.shape[0] * self.subbands, + self.gen_istft_n_fft // 2 + 1, + spec.shape[-1], + ), + ), + torch.reshape( + phase, + ( + phase.shape[0] * self.subbands, + self.gen_istft_n_fft // 2 + 1, + phase.shape[-1], + ), + ), + ) + y_mb_hat = torch.reshape( + y_mb_hat, (x.shape[0], self.subbands, 1, y_mb_hat.shape[-1]) + ) + y_mb_hat = y_mb_hat.squeeze(-2) + + y_mb_hat = F.conv_transpose1d( + y_mb_hat, + self.updown_filter.cuda(x.device) * self.subbands, + stride=self.subbands, + ) + + y_g_hat = self.multistream_conv_post(y_mb_hat) + + return y_g_hat, y_mb_hat + + def remove_weight_norm(self): + print("Removing weight norm...") + for l in self.ups: + remove_weight_norm(l) + for l in self.resblocks: + l.remove_weight_norm() diff --git a/src/so_vits_svc_fork/vdecoder/mb_istft/loss.py b/src/so_vits_svc_fork/vdecoder/mb_istft/loss.py new file mode 100644 index 00000000..9895befd --- /dev/null +++ b/src/so_vits_svc_fork/vdecoder/mb_istft/loss.py @@ -0,0 +1,11 @@ +from .stft_loss import MultiResolutionSTFTLoss + + +def subband_stft_loss(h, y_mb, y_hat_mb): + sub_stft_loss = MultiResolutionSTFTLoss( + h.train.fft_sizes, h.train.hop_sizes, h.train.win_lengths + ) + y_mb = y_mb.view(-1, y_mb.size(2)) + y_hat_mb = y_hat_mb.view(-1, y_hat_mb.size(2)) + sub_sc_loss, sub_mag_loss = sub_stft_loss(y_hat_mb[:, : y_mb.size(-1)], y_mb) + return sub_sc_loss + sub_mag_loss diff --git a/src/so_vits_svc_fork/vdecoder/mb_istft/pqmf.py b/src/so_vits_svc_fork/vdecoder/mb_istft/pqmf.py new file mode 100644 index 00000000..987dde8e --- /dev/null +++ b/src/so_vits_svc_fork/vdecoder/mb_istft/pqmf.py @@ -0,0 +1,130 @@ +# Copyright 2020 Tomoki Hayashi +# MIT License (https://opensource.org/licenses/MIT) + +"""Pseudo QMF modules.""" + +import numpy as np +import torch +import torch.nn.functional as F +from scipy.signal import kaiser + + +def design_prototype_filter(taps=62, cutoff_ratio=0.15, beta=9.0): + """Design prototype filter for PQMF. + This method is based on `A Kaiser window approach for the design of prototype + filters of cosine modulated filterbanks`_. + Args: + taps (int): The number of filter taps. + cutoff_ratio (float): Cut-off frequency ratio. + beta (float): Beta coefficient for kaiser window. + Returns: + ndarray: Impluse response of prototype filter (taps + 1,). + .. _`A Kaiser window approach for the design of prototype filters of cosine modulated filterbanks`: + https://ieeexplore.ieee.org/abstract/document/681427 + """ + # check the arguments are valid + assert taps % 2 == 0, "The number of taps mush be even number." + assert 0.0 < cutoff_ratio < 1.0, "Cutoff ratio must be > 0.0 and < 1.0." + + # make initial filter + omega_c = np.pi * cutoff_ratio + with np.errstate(invalid="ignore"): + h_i = np.sin(omega_c * (np.arange(taps + 1) - 0.5 * taps)) / ( + np.pi * (np.arange(taps + 1) - 0.5 * taps) + ) + h_i[taps // 2] = np.cos(0) * cutoff_ratio # fix nan due to indeterminate form + + # apply kaiser window + w = kaiser(taps + 1, beta) + h = h_i * w + + return h + + +class PQMF(torch.nn.Module): + """PQMF module. + This module is based on `Near-perfect-reconstruction pseudo-QMF banks`_. + .. _`Near-perfect-reconstruction pseudo-QMF banks`: + https://ieeexplore.ieee.org/document/258122 + """ + + def __init__(self, device, subbands=4, taps=62, cutoff_ratio=0.15, beta=9.0): + """Initialize PQMF module. + Args: + subbands (int): The number of subbands. + taps (int): The number of filter taps. + cutoff_ratio (float): Cut-off frequency ratio. + beta (float): Beta coefficient for kaiser window. + """ + super().__init__() + + # define filter coefficient + h_proto = design_prototype_filter(taps, cutoff_ratio, beta) + h_analysis = np.zeros((subbands, len(h_proto))) + h_synthesis = np.zeros((subbands, len(h_proto))) + for k in range(subbands): + h_analysis[k] = ( + 2 + * h_proto + * np.cos( + (2 * k + 1) + * (np.pi / (2 * subbands)) + * (np.arange(taps + 1) - ((taps - 1) / 2)) + + (-1) ** k * np.pi / 4 + ) + ) + h_synthesis[k] = ( + 2 + * h_proto + * np.cos( + (2 * k + 1) + * (np.pi / (2 * subbands)) + * (np.arange(taps + 1) - ((taps - 1) / 2)) + - (-1) ** k * np.pi / 4 + ) + ) + + # convert to tensor + analysis_filter = torch.from_numpy(h_analysis).float().unsqueeze(1).cuda(device) + synthesis_filter = ( + torch.from_numpy(h_synthesis).float().unsqueeze(0).cuda(device) + ) + + # register coefficients as buffer + self.register_buffer("analysis_filter", analysis_filter) + self.register_buffer("synthesis_filter", synthesis_filter) + + # filter for downsampling & upsampling + updown_filter = torch.zeros((subbands, subbands, subbands)).float().cuda(device) + for k in range(subbands): + updown_filter[k, k, 0] = 1.0 + self.register_buffer("updown_filter", updown_filter) + self.subbands = subbands + + # keep padding info + self.pad_fn = torch.nn.ConstantPad1d(taps // 2, 0.0) + + def analysis(self, x): + """Analysis with PQMF. + Args: + x (Tensor): Input tensor (B, 1, T). + Returns: + Tensor: Output tensor (B, subbands, T // subbands). + """ + x = F.conv1d(self.pad_fn(x), self.analysis_filter) + return F.conv1d(x, self.updown_filter, stride=self.subbands) + + def synthesis(self, x): + """Synthesis with PQMF. + Args: + x (Tensor): Input tensor (B, subbands, T // subbands). + Returns: + Tensor: Output tensor (B, 1, T). + """ + # NOTE(kan-bayashi): Power will be dreased so here multiply by # subbands. + # Not sure this is the correct way, it is better to check again. + # TODO(kan-bayashi): Understand the reconstruction procedure + x = F.conv_transpose1d( + x, self.updown_filter * self.subbands, stride=self.subbands + ) + return F.conv1d(self.pad_fn(x), self.synthesis_filter) diff --git a/src/so_vits_svc_fork/vdecoder/mb_istft/stft.py b/src/so_vits_svc_fork/vdecoder/mb_istft/stft.py new file mode 100644 index 00000000..8a111dca --- /dev/null +++ b/src/so_vits_svc_fork/vdecoder/mb_istft/stft.py @@ -0,0 +1,248 @@ +""" +BSD 3-Clause License +Copyright (c) 2017, Prem Seetharaman +All rights reserved. +* Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: +* Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright notice, this + list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from this + software without specific prior written permission. +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +""" + +import librosa.util as librosa_util +import numpy as np +import torch +import torch.nn.functional as F +from librosa.util import pad_center, tiny +from scipy.signal import get_window +from torch.autograd import Variable + + +def window_sumsquare( + window, + n_frames, + hop_length=200, + win_length=800, + n_fft=800, + dtype=np.float32, + norm=None, +): + """ + # from librosa 0.6 + Compute the sum-square envelope of a window function at a given hop length. + This is used to estimate modulation effects induced by windowing + observations in short-time fourier transforms. + Parameters + ---------- + window : string, tuple, number, callable, or list-like + Window specification, as in `get_window` + n_frames : int > 0 + The number of analysis frames + hop_length : int > 0 + The number of samples to advance between frames + win_length : [optional] + The length of the window function. By default, this matches `n_fft`. + n_fft : int > 0 + The length of each analysis frame. + dtype : np.dtype + The data type of the output + Returns + ------- + wss : np.ndarray, shape=`(n_fft + hop_length * (n_frames - 1))` + The sum-squared envelope of the window function + """ + if win_length is None: + win_length = n_fft + + n = n_fft + hop_length * (n_frames - 1) + x = np.zeros(n, dtype=dtype) + + # Compute the squared window at the desired length + win_sq = get_window(window, win_length, fftbins=True) + win_sq = librosa_util.normalize(win_sq, norm=norm) ** 2 + win_sq = librosa_util.pad_center(win_sq, n_fft) + + # Fill the envelope + for i in range(n_frames): + sample = i * hop_length + x[sample : min(n, sample + n_fft)] += win_sq[: max(0, min(n_fft, n - sample))] + return x + + +class STFT(torch.nn.Module): + """adapted from Prem Seetharaman's https://github.com/pseeth/pytorch-stft""" + + def __init__( + self, filter_length=800, hop_length=200, win_length=800, window="hann" + ): + super().__init__() + self.filter_length = filter_length + self.hop_length = hop_length + self.win_length = win_length + self.window = window + self.forward_transform = None + scale = self.filter_length / self.hop_length + fourier_basis = np.fft.fft(np.eye(self.filter_length)) + + cutoff = int(self.filter_length / 2 + 1) + fourier_basis = np.vstack( + [np.real(fourier_basis[:cutoff, :]), np.imag(fourier_basis[:cutoff, :])] + ) + + forward_basis = torch.FloatTensor(fourier_basis[:, None, :]) + inverse_basis = torch.FloatTensor( + np.linalg.pinv(scale * fourier_basis).T[:, None, :] + ) + + if window is not None: + assert filter_length >= win_length + # get window and zero center pad it to filter_length + fft_window = get_window(window, win_length, fftbins=True) + fft_window = pad_center(fft_window, filter_length) + fft_window = torch.from_numpy(fft_window).float() + + # window the bases + forward_basis *= fft_window + inverse_basis *= fft_window + + self.register_buffer("forward_basis", forward_basis.float()) + self.register_buffer("inverse_basis", inverse_basis.float()) + + def transform(self, input_data): + num_batches = input_data.size(0) + num_samples = input_data.size(1) + + self.num_samples = num_samples + + # similar to librosa, reflect-pad the input + input_data = input_data.view(num_batches, 1, num_samples) + input_data = F.pad( + input_data.unsqueeze(1), + (int(self.filter_length / 2), int(self.filter_length / 2), 0, 0), + mode="reflect", + ) + input_data = input_data.squeeze(1) + + forward_transform = F.conv1d( + input_data, + Variable(self.forward_basis, requires_grad=False), + stride=self.hop_length, + padding=0, + ) + + cutoff = int((self.filter_length / 2) + 1) + real_part = forward_transform[:, :cutoff, :] + imag_part = forward_transform[:, cutoff:, :] + + magnitude = torch.sqrt(real_part**2 + imag_part**2) + phase = torch.autograd.Variable(torch.atan2(imag_part.data, real_part.data)) + + return magnitude, phase + + def inverse(self, magnitude, phase): + recombine_magnitude_phase = torch.cat( + [magnitude * torch.cos(phase), magnitude * torch.sin(phase)], dim=1 + ) + + inverse_transform = F.conv_transpose1d( + recombine_magnitude_phase, + Variable(self.inverse_basis, requires_grad=False), + stride=self.hop_length, + padding=0, + ) + + if self.window is not None: + window_sum = window_sumsquare( + self.window, + magnitude.size(-1), + hop_length=self.hop_length, + win_length=self.win_length, + n_fft=self.filter_length, + dtype=np.float32, + ) + # remove modulation effects + approx_nonzero_indices = torch.from_numpy( + np.where(window_sum > tiny(window_sum))[0] + ) + window_sum = torch.autograd.Variable( + torch.from_numpy(window_sum), requires_grad=False + ) + window_sum = ( + window_sum.to(inverse_transform.device()) + if magnitude.is_cuda + else window_sum + ) + inverse_transform[:, :, approx_nonzero_indices] /= window_sum[ + approx_nonzero_indices + ] + + # scale by hop ratio + inverse_transform *= float(self.filter_length) / self.hop_length + + inverse_transform = inverse_transform[:, :, int(self.filter_length / 2) :] + inverse_transform = inverse_transform[:, :, : -int(self.filter_length / 2) :] + + return inverse_transform + + def forward(self, input_data): + self.magnitude, self.phase = self.transform(input_data) + reconstruction = self.inverse(self.magnitude, self.phase) + return reconstruction + + +class TorchSTFT(torch.nn.Module): + def __init__( + self, filter_length=800, hop_length=200, win_length=800, window="hann" + ): + super().__init__() + self.filter_length = filter_length + self.hop_length = hop_length + self.win_length = win_length + self.window = torch.from_numpy( + get_window(window, win_length, fftbins=True).astype(np.float32) + ) + + def transform(self, input_data): + forward_transform = torch.stft( + input_data, + self.filter_length, + self.hop_length, + self.win_length, + window=self.window, + return_complex=True, + ) + + return torch.abs(forward_transform), torch.angle(forward_transform) + + def inverse(self, magnitude, phase): + inverse_transform = torch.istft( + magnitude * torch.exp(phase * 1j), + self.filter_length, + self.hop_length, + self.win_length, + window=self.window.to(magnitude.device), + ) + + return inverse_transform.unsqueeze( + -2 + ) # unsqueeze to stay consistent with conv_transpose1d implementation + + def forward(self, input_data): + self.magnitude, self.phase = self.transform(input_data) + reconstruction = self.inverse(self.magnitude, self.phase) + return reconstruction diff --git a/src/so_vits_svc_fork/vdecoder/mb_istft/stft_loss.py b/src/so_vits_svc_fork/vdecoder/mb_istft/stft_loss.py new file mode 100644 index 00000000..ac30172d --- /dev/null +++ b/src/so_vits_svc_fork/vdecoder/mb_istft/stft_loss.py @@ -0,0 +1,140 @@ +# Copyright 2019 Tomoki Hayashi +# MIT License (https://opensource.org/licenses/MIT) + +"""STFT-based Loss modules.""" + +import torch +import torch.nn.functional as F + + +def stft(x, fft_size, hop_size, win_length, window): + """Perform STFT and convert to magnitude spectrogram. + Args: + x (Tensor): Input signal tensor (B, T). + fft_size (int): FFT size. + hop_size (int): Hop size. + win_length (int): Window length. + window (str): Window function type. + Returns: + Tensor: Magnitude spectrogram (B, #frames, fft_size // 2 + 1). + """ + x_stft = torch.stft(x, fft_size, hop_size, win_length, window.to(x.device)) + real = x_stft[..., 0] + imag = x_stft[..., 1] + + # NOTE(kan-bayashi): clamp is needed to avoid nan or inf + return torch.sqrt(torch.clamp(real**2 + imag**2, min=1e-7)).transpose(2, 1) + + +class SpectralConvergengeLoss(torch.nn.Module): + """Spectral convergence loss module.""" + + def __init__(self): + """Initialize spectral convergence loss module.""" + super().__init__() + + def forward(self, x_mag, y_mag): + """Calculate forward propagation. + Args: + x_mag (Tensor): Magnitude spectrogram of predicted signal (B, #frames, #freq_bins). + y_mag (Tensor): Magnitude spectrogram of groundtruth signal (B, #frames, #freq_bins). + Returns: + Tensor: Spectral convergence loss value. + """ + return torch.norm(y_mag - x_mag) / torch.norm( + y_mag + ) # MB-iSTFT-VITS changed here due to codespell + + +class LogSTFTMagnitudeLoss(torch.nn.Module): + """Log STFT magnitude loss module.""" + + def __init__(self): + """Initialize los STFT magnitude loss module.""" + super().__init__() + + def forward(self, x_mag, y_mag): + """Calculate forward propagation. + Args: + x_mag (Tensor): Magnitude spectrogram of predicted signal (B, #frames, #freq_bins). + y_mag (Tensor): Magnitude spectrogram of groundtruth signal (B, #frames, #freq_bins). + Returns: + Tensor: Log STFT magnitude loss value. + """ + return F.l1_loss(torch.log(y_mag), torch.log(x_mag)) + + +class STFTLoss(torch.nn.Module): + """STFT loss module.""" + + def __init__( + self, fft_size=1024, shift_size=120, win_length=600, window="hann_window" + ): + """Initialize STFT loss module.""" + super().__init__() + self.fft_size = fft_size + self.shift_size = shift_size + self.win_length = win_length + self.window = getattr(torch, window)(win_length) + self.spectral_convergenge_loss = SpectralConvergengeLoss() + self.log_stft_magnitude_loss = LogSTFTMagnitudeLoss() + + def forward(self, x, y): + """Calculate forward propagation. + Args: + x (Tensor): Predicted signal (B, T). + y (Tensor): Groundtruth signal (B, T). + Returns: + Tensor: Spectral convergence loss value. + Tensor: Log STFT magnitude loss value. + """ + x_mag = stft(x, self.fft_size, self.shift_size, self.win_length, self.window) + y_mag = stft(y, self.fft_size, self.shift_size, self.win_length, self.window) + sc_loss = self.spectral_convergenge_loss(x_mag, y_mag) + mag_loss = self.log_stft_magnitude_loss(x_mag, y_mag) + + return sc_loss, mag_loss + + +class MultiResolutionSTFTLoss(torch.nn.Module): + """Multi resolution STFT loss module.""" + + def __init__( + self, + fft_sizes=[1024, 2048, 512], + hop_sizes=[120, 240, 50], + win_lengths=[600, 1200, 240], + window="hann_window", + ): + """Initialize Multi resolution STFT loss module. + Args: + fft_sizes (list): List of FFT sizes. + hop_sizes (list): List of hop sizes. + win_lengths (list): List of window lengths. + window (str): Window function type. + """ + super().__init__() + assert len(fft_sizes) == len(hop_sizes) == len(win_lengths) + self.stft_losses = torch.nn.ModuleList() + for fs, ss, wl in zip(fft_sizes, hop_sizes, win_lengths): + self.stft_losses += [STFTLoss(fs, ss, wl, window)] + + def forward(self, x, y): + """Calculate forward propagation. + Args: + x (Tensor): Predicted signal (B, T). + y (Tensor): Groundtruth signal (B, T). + Returns: + Tensor: Multi resolution spectral convergence loss value. + Tensor: Multi resolution log STFT magnitude loss value. + """ + sc_loss = 0.0 + mag_loss = 0.0 + for f in self.stft_losses: + sc_l, mag_l = f(x, y) + sc_loss += sc_l + mag_loss += mag_l + sc_loss /= len(self.stft_losses) + mag_loss /= len(self.stft_losses) + + return sc_loss, mag_loss From 5b3fb65ff6645daeda69123e569e5ec3c91f433a Mon Sep 17 00:00:00 2001 From: 34j <55338215+34j@users.noreply.github.com> Date: Fri, 31 Mar 2023 22:08:48 +0900 Subject: [PATCH 05/47] fix(__main__): fix automatic model search algo --- src/so_vits_svc_fork/__main__.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/so_vits_svc_fork/__main__.py b/src/so_vits_svc_fork/__main__.py index b2660bdb..0e639710 100644 --- a/src/so_vits_svc_fork/__main__.py +++ b/src/so_vits_svc_fork/__main__.py @@ -222,7 +222,9 @@ def infer( output_path = Path(output_path) model_path = Path(model_path) if model_path.is_dir(): - model_path = list(sorted(model_path.glob("*.pth")))[-1] + model_path = list( + sorted(model_path.glob("G_*.pth"), key=lambda x: x.stat().st_mtime) + )[-1] LOG.info(f"Since model_path is a directory, use {model_path}") config_path = Path(config_path) if cluster_model_path is not None: @@ -381,7 +383,9 @@ def vc( if cluster_model_path is not None: cluster_model_path = Path(cluster_model_path) if model_path.is_dir(): - model_path = list(sorted(model_path.glob("*.pth")))[-1] + model_path = list( + sorted(model_path.glob("G_*.pth"), key=lambda x: x.stat().st_mtime) + )[-1] LOG.info(f"Since model_path is a directory, use {model_path}") realtime( From 1ce2580148ebcf89e03e4da174ec5c06ab7445c1 Mon Sep 17 00:00:00 2001 From: 34j <55338215+34j@users.noreply.github.com> Date: Fri, 31 Mar 2023 22:23:34 +0900 Subject: [PATCH 06/47] fix(train): add loss calculation --- src/so_vits_svc_fork/train.py | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/so_vits_svc_fork/train.py b/src/so_vits_svc_fork/train.py index 515d0ebc..e0959410 100644 --- a/src/so_vits_svc_fork/train.py +++ b/src/so_vits_svc_fork/train.py @@ -217,6 +217,7 @@ def train_and_evaluate( with autocast(enabled=hps.train.fp16_run): ( y_hat, + y_hat_mb, ids_slice, z_mask, (z, z_p, m_p, logs_p, m_q, logs_q), @@ -270,12 +271,12 @@ def train_and_evaluate( # MB-iSTFT-VITS loss_subband = torch.tensor(0.0) - if hps.model.__dict__.get("type_") == "mb-istft-vits": + if hps.model.type_ == "mb-istft": from .vdecoder.mb_istft.loss import subband_stft_loss from .vdecoder.mb_istft.pqmf import PQMF - y_mb = PQMF(y.device).analysis(y) - loss_subband = subband_stft_loss(hps, y_mb, y_hat) + y_mb = PQMF(y.device, hps.model.subbands).analysis(y) + loss_subband = subband_stft_loss(hps, y_mb, y_hat_mb) loss_gen_all += loss_subband optim_g.zero_grad() @@ -295,7 +296,7 @@ def train_and_evaluate( "melspectrogram": loss_mel.item(), "kl_divergence": loss_kl.item(), } - if hps.model.__dict__.get("type_") == "mb-istft-vits": + if hps.model.type_ == "mb-istft": losses["subband_stft"] = loss_subband.item() LOG.info( "Train Epoch: {} [{:.0f}%]".format( @@ -317,10 +318,10 @@ def train_and_evaluate( "loss/g/mel": loss_mel, "loss/g/kl": loss_kl, "loss/g/lf0": loss_lf0, - # MB-iSTFT-VITS - "loss/g/subband": loss_subband, } ) + if hps.model.type_ == "mb-istft": + scalar_dict["loss/g/subband"] = loss_subband # scalar_dict.update({"loss/g/{}".format(i): v for i, v in enumerate(losses_gen)}) # scalar_dict.update({"loss/d_r/{}".format(i): v for i, v in enumerate(losses_disc_r)}) From cc463db98cb334ced7e70319c45965bf14d3e9a3 Mon Sep 17 00:00:00 2001 From: 34j <55338215+34j@users.noreply.github.com> Date: Fri, 31 Mar 2023 22:24:05 +0900 Subject: [PATCH 07/47] fix(infer_tool): half=False by default --- src/so_vits_svc_fork/inference/infer_tool.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/so_vits_svc_fork/inference/infer_tool.py b/src/so_vits_svc_fork/inference/infer_tool.py index 9a2e1c09..462ef3d6 100644 --- a/src/so_vits_svc_fork/inference/infer_tool.py +++ b/src/so_vits_svc_fork/inference/infer_tool.py @@ -94,7 +94,7 @@ def __init__( config_path: str, device: torch.device | str | None = None, cluster_model_path: Path | str | None = None, - half: bool = True, + half: bool = False, ): self.net_g_path = net_g_path if device is None: From aac151ae6a247e9a8d130cd078c9a8075a30c693 Mon Sep 17 00:00:00 2001 From: 34j <55338215+34j@users.noreply.github.com> Date: Fri, 31 Mar 2023 22:24:48 +0900 Subject: [PATCH 08/47] fix(stft_loss): return_complex = False --- src/so_vits_svc_fork/vdecoder/mb_istft/stft_loss.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/so_vits_svc_fork/vdecoder/mb_istft/stft_loss.py b/src/so_vits_svc_fork/vdecoder/mb_istft/stft_loss.py index ac30172d..c685cb02 100644 --- a/src/so_vits_svc_fork/vdecoder/mb_istft/stft_loss.py +++ b/src/so_vits_svc_fork/vdecoder/mb_istft/stft_loss.py @@ -18,7 +18,9 @@ def stft(x, fft_size, hop_size, win_length, window): Returns: Tensor: Magnitude spectrogram (B, #frames, fft_size // 2 + 1). """ - x_stft = torch.stft(x, fft_size, hop_size, win_length, window.to(x.device)) + x_stft = torch.stft( + x, fft_size, hop_size, win_length, window.to(x.device), return_complex=False + ) real = x_stft[..., 0] imag = x_stft[..., 1] From b84788563d48f3d3da6d08b8897fd109e5d03b2b Mon Sep 17 00:00:00 2001 From: 34j <55338215+34j@users.noreply.github.com> Date: Fri, 31 Mar 2023 22:27:02 +0900 Subject: [PATCH 09/47] fix: update hps --- .../configs_template/config_template.json | 23 ++++-- src/so_vits_svc_fork/models.py | 80 +++++++++++-------- .../vdecoder/mb_istft/generators.py | 2 +- 3 files changed, 65 insertions(+), 40 deletions(-) diff --git a/src/so_vits_svc_fork/configs_template/config_template.json b/src/so_vits_svc_fork/configs_template/config_template.json index 45852762..1116c0a8 100644 --- a/src/so_vits_svc_fork/configs_template/config_template.json +++ b/src/so_vits_svc_fork/configs_template/config_template.json @@ -7,7 +7,7 @@ "learning_rate": 0.0001, "betas": [0.8, 0.99], "eps": 1e-9, - "batch_size": 6, + "batch_size": 2, "fp16_run": false, "lr_decay": 0.999875, "segment_size": 10240, @@ -18,7 +18,11 @@ "use_sr": true, "max_speclen": 512, "port": "8001", - "keep_ckpts": 3 + "keep_ckpts": 3, + "fft_sizes": [384, 683, 171], + "hop_sizes": [30, 60, 10], + "win_lengths": [150, 300, 60], + "window": "hann_window" }, "data": { "training_files": "filelists/44k/train.txt", @@ -47,14 +51,21 @@ [1, 3, 5], [1, 3, 5] ], - "upsample_rates": [8, 8, 2, 2, 2], + "upsample_rates": [4, 4], "upsample_initial_channel": 512, - "upsample_kernel_sizes": [16, 16, 4, 4, 4], + "upsample_kernel_sizes": [16, 16], "n_layers_q": 3, "use_spectral_norm": false, "gin_channels": 256, "ssl_dim": 256, - "n_speakers": 200 + "n_speakers": 200, + "type_": "mb-istft", + "gen_istft_n_fft": 16, + "gen_istft_hop_size": 4, + "subbands": 8 }, - "spk": {} + "spk": { + "34j": 0, + "kiritan": 1 + } } diff --git a/src/so_vits_svc_fork/models.py b/src/so_vits_svc_fork/models.py index fd2da327..1d369efd 100644 --- a/src/so_vits_svc_fork/models.py +++ b/src/so_vits_svc_fork/models.py @@ -1,5 +1,5 @@ from logging import getLogger -from typing import Literal +from typing import Any, Literal, Sequence import torch from torch import nn @@ -378,30 +378,30 @@ class SynthesizerTrn(nn.Module): def __init__( self, - spec_channels, - segment_size, - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - gin_channels, - ssl_dim, - n_speakers, - sampling_rate=44100, + spec_channels: int, + segment_size: int, + inter_channels: int, + hidden_channels: int, + filter_channels: int, + n_heads: int, + n_layers: int, + kernel_size: int, + p_dropout: int, + resblock: str, + resblock_kernel_sizes: Sequence[int], + resblock_dilation_sizes: Sequence[Sequence[int]], + upsample_rates: Sequence[int], + upsample_initial_channel: int, + upsample_kernel_sizes: Sequence[int], + gin_channels: int, + ssl_dim: int, + n_speakers: int, + sampling_rate: int = 44100, type_: Literal["hifi-gan", "istft", "ms-istft", "mb-istft"] = "hifi-gan", gen_istft_n_fft: int = 16, gen_istft_hop_size: int = 4, - subbands: bool = False, - **kwargs, + subbands: int = 8, + **kwargs: Any, ): super().__init__() self.spec_channels = spec_channels @@ -434,23 +434,36 @@ def __init__( kernel_size=kernel_size, p_dropout=p_dropout, ) - hps = { - "sampling_rate": sampling_rate, - "inter_channels": inter_channels, - "resblock": resblock, - "resblock_kernel_sizes": resblock_kernel_sizes, - "resblock_dilation_sizes": resblock_dilation_sizes, - "upsample_rates": upsample_rates, - "upsample_initial_channel": upsample_initial_channel, - "upsample_kernel_sizes": upsample_kernel_sizes, - "gin_channels": gin_channels, - } LOG.info(f"Decoder type: {type_}") if type_ == "hifi-gan": + hps = { + "sampling_rate": sampling_rate, + "inter_channels": inter_channels, + "resblock": resblock, + "resblock_kernel_sizes": resblock_kernel_sizes, + "resblock_dilation_sizes": resblock_dilation_sizes, + "upsample_rates": upsample_rates, + "upsample_initial_channel": upsample_initial_channel, + "upsample_kernel_sizes": upsample_kernel_sizes, + "gin_channels": gin_channels, + } self.dec = Generator(h=hps) self.mb = False else: + hps = { + "initial_channel": inter_channels, + "resblock": resblock, + "resblock_kernel_sizes": resblock_kernel_sizes, + "resblock_dilation_sizes": resblock_dilation_sizes, + "upsample_rates": upsample_rates, + "upsample_initial_channel": upsample_initial_channel, + "upsample_kernel_sizes": upsample_kernel_sizes, + "gin_channels": gin_channels, + "gen_istft_n_fft": gen_istft_n_fft, + "gen_istft_hop_size": gen_istft_hop_size, + "subbands": subbands, + } from .vdecoder.mb_istft.generators import ( Multiband_iSTFT_Generator, Multistream_iSTFT_Generator, @@ -459,6 +472,7 @@ def __init__( # gen_istft_n_fft, gen_istft_hop_size, subbands if type_ == "istft": + del hps["subbands"] self.dec = iSTFT_Generator(**hps) elif type_ == "ms-istft": self.dec = Multistream_iSTFT_Generator(**hps) diff --git a/src/so_vits_svc_fork/vdecoder/mb_istft/generators.py b/src/so_vits_svc_fork/vdecoder/mb_istft/generators.py index c5e469a4..95ff98c1 100644 --- a/src/so_vits_svc_fork/vdecoder/mb_istft/generators.py +++ b/src/so_vits_svc_fork/vdecoder/mb_istft/generators.py @@ -168,7 +168,7 @@ def forward(self, x, g=None): hop_length=self.gen_istft_hop_size, win_length=self.gen_istft_n_fft, ).to(x.device) - pqmf = PQMF(x.device) + pqmf = PQMF(x.device, subbands=self.subbands).to(x.device, dtype=x.dtype) x = self.conv_pre(x) # [B, ch, length] From 8f7476634dcd88261078549d0aa472b4506b46ec Mon Sep 17 00:00:00 2001 From: 34j <55338215+34j@users.noreply.github.com> Date: Fri, 31 Mar 2023 23:36:53 +0900 Subject: [PATCH 10/47] fix(train): remove ensure_pretrained_model --- src/so_vits_svc_fork/train.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/so_vits_svc_fork/train.py b/src/so_vits_svc_fork/train.py index e0959410..fb797b59 100644 --- a/src/so_vits_svc_fork/train.py +++ b/src/so_vits_svc_fork/train.py @@ -39,7 +39,7 @@ def train(config_path: Path | str, model_path: Path | str): model_path = Path(model_path) if not torch.cuda.is_available(): raise RuntimeError("CUDA is not available.") - utils.ensure_pretrained_model(model_path) + # utils.ensure_pretrained_model(model_path) hps = utils.get_hparams(config_path, model_path) n_gpus = torch.cuda.device_count() From c61dd17192cf452e7ab7a35f00f741d6c2b93ccf Mon Sep 17 00:00:00 2001 From: 34j <55338215+34j@users.noreply.github.com> Date: Fri, 31 Mar 2023 23:37:48 +0900 Subject: [PATCH 11/47] fix(mel_processing): fix wrong logging --- src/so_vits_svc_fork/modules/mel_processing.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/so_vits_svc_fork/modules/mel_processing.py b/src/so_vits_svc_fork/modules/mel_processing.py index ff3ad9cd..0de6e54b 100644 --- a/src/so_vits_svc_fork/modules/mel_processing.py +++ b/src/so_vits_svc_fork/modules/mel_processing.py @@ -99,9 +99,9 @@ def mel_spectrogram_torch( y, n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax, center=False ): if torch.min(y) < -1.0: - LOG.info("min value is ", torch.min(y)) + LOG.info(f"min value is {torch.min(y)}") if torch.max(y) > 1.0: - LOG.info("max value is ", torch.max(y)) + LOG.info(f"max value is {torch.max(y)}") global mel_basis, hann_window dtype_device = str(y.dtype) + "_" + str(y.device) From 21feb01a0400eeeb48fd1f91fcb37c4545df7240 Mon Sep 17 00:00:00 2001 From: 34j <55338215+34j@users.noreply.github.com> Date: Sat, 1 Apr 2023 12:55:34 +0900 Subject: [PATCH 12/47] refactor: refactor a lot BREAKING CHANGE: this is a breaking change --- .idea/workspace.xml | 73 ++- src/so_vits_svc_fork/__main__.py | 18 +- src/so_vits_svc_fork/data_utils.py | 4 +- src/so_vits_svc_fork/f0.py | 237 ++++++++ src/so_vits_svc_fork/gui.py | 6 +- src/so_vits_svc_fork/hparams.py | 33 + src/so_vits_svc_fork/inference/infer_tool.py | 13 +- .../{ => inference}/inference_main.py | 2 +- src/so_vits_svc_fork/models.py | 574 ------------------ .../decoders}/__init__.py | 0 src/so_vits_svc_fork/modules/decoders/f0.py | 45 ++ .../modules/decoders/hifigan/__init__.py | 3 + .../decoders/hifigan/_models.py} | 2 +- .../decoders/hifigan/_utils.py} | 0 .../modules/decoders/mb_istft/__init__.py | 15 + .../decoders/mb_istft/_generators.py} | 4 +- .../decoders/mb_istft/_loss.py} | 2 +- .../decoders/mb_istft/_pqmf.py} | 2 +- .../decoders/mb_istft/_stft.py} | 0 .../decoders/mb_istft/_stft_loss.py} | 0 .../modules/descriminators.py | 144 +++++ src/so_vits_svc_fork/modules/encoders.py | 136 +++++ src/so_vits_svc_fork/modules/flows.py | 48 ++ src/so_vits_svc_fork/modules/generator.py | 220 +++++++ .../{vdecoder => modules/onnx}/__init__.py | 0 .../onnx}/model_onnx.py | 14 +- .../{ => modules/onnx}/onnx_export.py | 4 +- .../hifigan => preprocessing}/__init__.py | 0 .../preprocess_flist_config.py | 0 .../preprocess_hubert_f0.py | 8 +- .../preprocess_resample.py | 0 .../preprocess_speaker_diarization.py | 0 .../{ => preprocessing}/preprocess_split.py | 0 .../{ => preprocessing}/preprocess_utils.py | 0 src/so_vits_svc_fork/spec_gen.py | 23 - src/so_vits_svc_fork/train.py | 12 +- src/so_vits_svc_fork/utils.py | 313 +--------- .../{vdecoder/mb_istft => utils}/__init__.py | 0 src/so_vits_svc_fork/utils/f0py | 0 tests/test_main.py | 26 +- 40 files changed, 1036 insertions(+), 945 deletions(-) create mode 100644 src/so_vits_svc_fork/f0.py create mode 100644 src/so_vits_svc_fork/hparams.py rename src/so_vits_svc_fork/{ => inference}/inference_main.py (98%) delete mode 100644 src/so_vits_svc_fork/models.py rename src/so_vits_svc_fork/{onnxexport => modules/decoders}/__init__.py (100%) create mode 100644 src/so_vits_svc_fork/modules/decoders/f0.py create mode 100644 src/so_vits_svc_fork/modules/decoders/hifigan/__init__.py rename src/so_vits_svc_fork/{vdecoder/hifigan/models.py => modules/decoders/hifigan/_models.py} (99%) rename src/so_vits_svc_fork/{vdecoder/hifigan/utils.py => modules/decoders/hifigan/_utils.py} (100%) create mode 100644 src/so_vits_svc_fork/modules/decoders/mb_istft/__init__.py rename src/so_vits_svc_fork/{vdecoder/mb_istft/generators.py => modules/decoders/mb_istft/_generators.py} (99%) rename src/so_vits_svc_fork/{vdecoder/mb_istft/loss.py => modules/decoders/mb_istft/_loss.py} (88%) rename src/so_vits_svc_fork/{vdecoder/mb_istft/pqmf.py => modules/decoders/mb_istft/_pqmf.py} (98%) rename src/so_vits_svc_fork/{vdecoder/mb_istft/stft.py => modules/decoders/mb_istft/_stft.py} (100%) rename src/so_vits_svc_fork/{vdecoder/mb_istft/stft_loss.py => modules/decoders/mb_istft/_stft_loss.py} (100%) create mode 100644 src/so_vits_svc_fork/modules/descriminators.py create mode 100644 src/so_vits_svc_fork/modules/encoders.py create mode 100644 src/so_vits_svc_fork/modules/flows.py create mode 100644 src/so_vits_svc_fork/modules/generator.py rename src/so_vits_svc_fork/{vdecoder => modules/onnx}/__init__.py (100%) rename src/so_vits_svc_fork/{onnxexport => modules/onnx}/model_onnx.py (97%) rename src/so_vits_svc_fork/{ => modules/onnx}/onnx_export.py (94%) rename src/so_vits_svc_fork/{vdecoder/hifigan => preprocessing}/__init__.py (100%) rename src/so_vits_svc_fork/{ => preprocessing}/preprocess_flist_config.py (100%) rename src/so_vits_svc_fork/{ => preprocessing}/preprocess_hubert_f0.py (95%) rename src/so_vits_svc_fork/{ => preprocessing}/preprocess_resample.py (100%) rename src/so_vits_svc_fork/{ => preprocessing}/preprocess_speaker_diarization.py (100%) rename src/so_vits_svc_fork/{ => preprocessing}/preprocess_split.py (100%) rename src/so_vits_svc_fork/{ => preprocessing}/preprocess_utils.py (100%) delete mode 100644 src/so_vits_svc_fork/spec_gen.py rename src/so_vits_svc_fork/{vdecoder/mb_istft => utils}/__init__.py (100%) create mode 100644 src/so_vits_svc_fork/utils/f0py diff --git a/.idea/workspace.xml b/.idea/workspace.xml index 4c57db80..60a45bf0 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -2,16 +2,68 @@ + + + + + + + + - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -19,6 +71,9 @@