Upload custom-code python model
Browse files- configuration_bert_vits2.py +274 -0
- modeling_bert_vits2.py +1674 -0
- processing_bert_vits2.py +240 -0
- tokenization_bert_vits2.py +237 -0
configuration_bert_vits2.py
ADDED
@@ -0,0 +1,274 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2023 The Kakao Enterprise Authors and the HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
"""VITS model configuration"""
|
16 |
+
|
17 |
+
from typing import List
|
18 |
+
|
19 |
+
from transformers.configuration_utils import PretrainedConfig
|
20 |
+
from transformers.utils import logging
|
21 |
+
from transformers.models.bert.configuration_bert import BertConfig
|
22 |
+
import copy
|
23 |
+
|
24 |
+
|
25 |
+
logger = logging.get_logger(__name__)
|
26 |
+
|
27 |
+
|
28 |
+
class BertVits2Config(PretrainedConfig):
|
29 |
+
r"""
|
30 |
+
This is the configuration class to store the configuration of a [`BertVits2Model`]. It is used to instantiate a VITS
|
31 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
32 |
+
defaults will yield a similar configuration to that of the VITS
|
33 |
+
[facebook/mms-tts-eng](https://huggingface.co/facebook/mms-tts-eng) architecture.
|
34 |
+
|
35 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
36 |
+
documentation from [`PretrainedConfig`] for more information.
|
37 |
+
|
38 |
+
Args:
|
39 |
+
vocab_size (`int`, *optional*, defaults to 38):
|
40 |
+
Vocabulary size of the VITS model. Defines the number of different tokens that can be represented by the
|
41 |
+
`inputs_ids` passed to the forward method of [`BertVits2Model`].
|
42 |
+
hidden_size (`int`, *optional*, defaults to 192):
|
43 |
+
Dimensionality of the text encoder layers.
|
44 |
+
num_hidden_layers (`int`, *optional*, defaults to 6):
|
45 |
+
Number of hidden layers in the Transformer encoder.
|
46 |
+
num_attention_heads (`int`, *optional*, defaults to 2):
|
47 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
48 |
+
window_size (`int`, *optional*, defaults to 4):
|
49 |
+
Window size for the relative positional embeddings in the attention layers of the Transformer encoder.
|
50 |
+
use_bias (`bool`, *optional*, defaults to `True`):
|
51 |
+
Whether to use bias in the key, query, value projection layers in the Transformer encoder.
|
52 |
+
ffn_dim (`int`, *optional*, defaults to 768):
|
53 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
54 |
+
layerdrop (`float`, *optional*, defaults to 0.1):
|
55 |
+
The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
|
56 |
+
for more details.
|
57 |
+
ffn_kernel_size (`int`, *optional*, defaults to 3):
|
58 |
+
Kernel size of the 1D convolution layers used by the feed-forward network in the Transformer encoder.
|
59 |
+
flow_size (`int`, *optional*, defaults to 192):
|
60 |
+
Dimensionality of the flow layers.
|
61 |
+
spectrogram_bins (`int`, *optional*, defaults to 513):
|
62 |
+
Number of frequency bins in the target spectrogram.
|
63 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"relu"`):
|
64 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
65 |
+
`"relu"`, `"selu"` and `"gelu_new"` are supported.
|
66 |
+
hidden_dropout (`float`, *optional*, defaults to 0.1):
|
67 |
+
The dropout probability for all fully connected layers in the embeddings and encoder.
|
68 |
+
attention_dropout (`float`, *optional*, defaults to 0.1):
|
69 |
+
The dropout ratio for the attention probabilities.
|
70 |
+
activation_dropout (`float`, *optional*, defaults to 0.1):
|
71 |
+
The dropout ratio for activations inside the fully connected layer.
|
72 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
73 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
74 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-05):
|
75 |
+
The epsilon used by the layer normalization layers.
|
76 |
+
use_stochastic_duration_prediction (`bool`, *optional*, defaults to `True`):
|
77 |
+
Whether to use the stochastic duration prediction module or the regular duration predictor.
|
78 |
+
num_speakers (`int`, *optional*, defaults to 1):
|
79 |
+
Number of speakers if this is a multi-speaker model.
|
80 |
+
speaker_embedding_size (`int`, *optional*, defaults to 0):
|
81 |
+
Number of channels used by the speaker embeddings. Is zero for single-speaker models.
|
82 |
+
upsample_initial_channel (`int`, *optional*, defaults to 512):
|
83 |
+
The number of input channels into the HiFi-GAN upsampling network.
|
84 |
+
upsample_rates (`Tuple[int]` or `List[int]`, *optional*, defaults to `[8, 8, 2, 2]`):
|
85 |
+
A tuple of integers defining the stride of each 1D convolutional layer in the HiFi-GAN upsampling network.
|
86 |
+
The length of `upsample_rates` defines the number of convolutional layers and has to match the length of
|
87 |
+
`upsample_kernel_sizes`.
|
88 |
+
upsample_kernel_sizes (`Tuple[int]` or `List[int]`, *optional*, defaults to `[16, 16, 4, 4]`):
|
89 |
+
A tuple of integers defining the kernel size of each 1D convolutional layer in the HiFi-GAN upsampling
|
90 |
+
network. The length of `upsample_kernel_sizes` defines the number of convolutional layers and has to match
|
91 |
+
the length of `upsample_rates`.
|
92 |
+
resblock_kernel_sizes (`Tuple[int]` or `List[int]`, *optional*, defaults to `[3, 7, 11]`):
|
93 |
+
A tuple of integers defining the kernel sizes of the 1D convolutional layers in the HiFi-GAN
|
94 |
+
multi-receptive field fusion (MRF) module.
|
95 |
+
resblock_dilation_sizes (`Tuple[Tuple[int]]` or `List[List[int]]`, *optional*, defaults to `[[1, 3, 5], [1, 3, 5], [1, 3, 5]]`):
|
96 |
+
A nested tuple of integers defining the dilation rates of the dilated 1D convolutional layers in the
|
97 |
+
HiFi-GAN multi-receptive field fusion (MRF) module.
|
98 |
+
leaky_relu_slope (`float`, *optional*, defaults to 0.1):
|
99 |
+
The angle of the negative slope used by the leaky ReLU activation.
|
100 |
+
depth_separable_channels (`int`, *optional*, defaults to 2):
|
101 |
+
Number of channels to use in each depth-separable block.
|
102 |
+
depth_separable_num_layers (`int`, *optional*, defaults to 3):
|
103 |
+
Number of convolutional layers to use in each depth-separable block.
|
104 |
+
duration_predictor_flow_bins (`int`, *optional*, defaults to 10):
|
105 |
+
Number of channels to map using the unonstrained rational spline in the duration predictor model.
|
106 |
+
duration_predictor_tail_bound (`float`, *optional*, defaults to 5.0):
|
107 |
+
Value of the tail bin boundary when computing the unconstrained rational spline in the duration predictor
|
108 |
+
model.
|
109 |
+
duration_predictor_kernel_size (`int`, *optional*, defaults to 3):
|
110 |
+
Kernel size of the 1D convolution layers used in the duration predictor model.
|
111 |
+
duration_predictor_dropout (`float`, *optional*, defaults to 0.5):
|
112 |
+
The dropout ratio for the duration predictor model.
|
113 |
+
duration_predictor_num_flows (`int`, *optional*, defaults to 4):
|
114 |
+
Number of flow stages used by the duration predictor model.
|
115 |
+
duration_predictor_filter_channels (`int`, *optional*, defaults to 256):
|
116 |
+
Number of channels for the convolution layers used in the duration predictor model.
|
117 |
+
prior_encoder_num_flows (`int`, *optional*, defaults to 4):
|
118 |
+
Number of flow stages used by the prior encoder flow model.
|
119 |
+
prior_encoder_num_wavenet_layers (`int`, *optional*, defaults to 4):
|
120 |
+
Number of WaveNet layers used by the prior encoder flow model.
|
121 |
+
posterior_encoder_num_wavenet_layers (`int`, *optional*, defaults to 16):
|
122 |
+
Number of WaveNet layers used by the posterior encoder model.
|
123 |
+
wavenet_kernel_size (`int`, *optional*, defaults to 5):
|
124 |
+
Kernel size of the 1D convolution layers used in the WaveNet model.
|
125 |
+
wavenet_dilation_rate (`int`, *optional*, defaults to 1):
|
126 |
+
Dilation rates of the dilated 1D convolutional layers used in the WaveNet model.
|
127 |
+
wavenet_dropout (`float`, *optional*, defaults to 0.0):
|
128 |
+
The dropout ratio for the WaveNet layers.
|
129 |
+
speaking_rate (`float`, *optional*, defaults to 1.0):
|
130 |
+
Speaking rate. Larger values give faster synthesised speech.
|
131 |
+
noise_scale (`float`, *optional*, defaults to 0.667):
|
132 |
+
How random the speech prediction is. Larger values create more variation in the predicted speech.
|
133 |
+
noise_scale_duration (`float`, *optional*, defaults to 0.8):
|
134 |
+
How random the duration prediction is. Larger values create more variation in the predicted durations.
|
135 |
+
sampling_rate (`int`, *optional*, defaults to 16000):
|
136 |
+
The sampling rate at which the output audio waveform is digitalized expressed in hertz (Hz).
|
137 |
+
|
138 |
+
Example:
|
139 |
+
|
140 |
+
```python
|
141 |
+
>>> from transformers import BertVits2Model, BertVits2Config
|
142 |
+
|
143 |
+
>>> # Initializing a "facebook/mms-tts-eng" style configuration
|
144 |
+
>>> configuration = BertVits2Config()
|
145 |
+
|
146 |
+
>>> # Initializing a model (with random weights) from the "facebook/mms-tts-eng" style configuration
|
147 |
+
>>> model = BertVits2Model(configuration)
|
148 |
+
|
149 |
+
>>> # Accessing the model configuration
|
150 |
+
>>> configuration = model.config
|
151 |
+
```"""
|
152 |
+
|
153 |
+
model_type = "bert_vits2"
|
154 |
+
|
155 |
+
def __init__(
|
156 |
+
self,
|
157 |
+
vocab_size=38,
|
158 |
+
hidden_size=192,
|
159 |
+
num_tones=12,
|
160 |
+
num_languages=1,
|
161 |
+
num_hidden_layers=6,
|
162 |
+
num_attention_heads=2,
|
163 |
+
window_size=4,
|
164 |
+
use_bias=True,
|
165 |
+
ffn_dim=768,
|
166 |
+
layerdrop=0.1,
|
167 |
+
ffn_kernel_size=3,
|
168 |
+
flow_size=192,
|
169 |
+
spectrogram_bins=513,
|
170 |
+
hidden_act="relu",
|
171 |
+
hidden_dropout=0.1,
|
172 |
+
attention_dropout=0.1,
|
173 |
+
activation_dropout=0.1,
|
174 |
+
initializer_range=0.02,
|
175 |
+
layer_norm_eps=1e-5,
|
176 |
+
use_transformer_flow=True,
|
177 |
+
num_speakers=1,
|
178 |
+
speaker_embedding_size=0,
|
179 |
+
upsample_initial_channel=512,
|
180 |
+
upsample_rates=[8, 8, 2, 2],
|
181 |
+
upsample_kernel_sizes=[16, 16, 4, 4],
|
182 |
+
resblock_kernel_sizes=[3, 7, 11],
|
183 |
+
resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5], [1, 3, 5]],
|
184 |
+
leaky_relu_slope=0.1,
|
185 |
+
depth_separable_channels=2,
|
186 |
+
depth_separable_num_layers=3,
|
187 |
+
duration_predictor_flow_bins=10,
|
188 |
+
duration_predictor_tail_bound=5.0,
|
189 |
+
duration_predictor_kernel_size=3,
|
190 |
+
duration_predictor_dropout=0.5,
|
191 |
+
duration_predictor_num_flows=4,
|
192 |
+
duration_predictor_filter_channels=256,
|
193 |
+
prior_encoder_num_flows=4,
|
194 |
+
prior_encoder_num_flows_layers=6,
|
195 |
+
prior_encoder_num_wavenet_layers=4,
|
196 |
+
posterior_encoder_num_wavenet_layers=16,
|
197 |
+
wavenet_kernel_size=5,
|
198 |
+
wavenet_dilation_rate=1,
|
199 |
+
wavenet_dropout=0.0,
|
200 |
+
conditioning_layer_index=2,
|
201 |
+
speaking_rate=1.0,
|
202 |
+
noise_scale=0.667,
|
203 |
+
noise_scale_duration=0.8,
|
204 |
+
stochastic_duration_prediction_ratio=0.0,
|
205 |
+
sampling_rate=16_000,
|
206 |
+
bert_configs = [],
|
207 |
+
**kwargs,
|
208 |
+
):
|
209 |
+
self.vocab_size = vocab_size
|
210 |
+
self.hidden_size = hidden_size
|
211 |
+
self.num_tones = num_tones
|
212 |
+
self.num_languages = num_languages
|
213 |
+
self.num_hidden_layers = num_hidden_layers
|
214 |
+
self.num_attention_heads = num_attention_heads
|
215 |
+
self.window_size = window_size
|
216 |
+
self.use_bias = use_bias
|
217 |
+
self.ffn_dim = ffn_dim
|
218 |
+
self.layerdrop = layerdrop
|
219 |
+
self.ffn_kernel_size = ffn_kernel_size
|
220 |
+
self.flow_size = flow_size
|
221 |
+
self.spectrogram_bins = spectrogram_bins
|
222 |
+
self.hidden_act = hidden_act
|
223 |
+
self.hidden_dropout = hidden_dropout
|
224 |
+
self.attention_dropout = attention_dropout
|
225 |
+
self.activation_dropout = activation_dropout
|
226 |
+
self.initializer_range = initializer_range
|
227 |
+
self.layer_norm_eps = layer_norm_eps
|
228 |
+
self.use_transformer_flow = use_transformer_flow
|
229 |
+
self.num_speakers = num_speakers
|
230 |
+
self.speaker_embedding_size = speaker_embedding_size
|
231 |
+
self.upsample_initial_channel = upsample_initial_channel
|
232 |
+
self.upsample_rates = upsample_rates
|
233 |
+
self.upsample_kernel_sizes = upsample_kernel_sizes
|
234 |
+
self.resblock_kernel_sizes = resblock_kernel_sizes
|
235 |
+
self.resblock_dilation_sizes = resblock_dilation_sizes
|
236 |
+
self.leaky_relu_slope = leaky_relu_slope
|
237 |
+
self.depth_separable_channels = depth_separable_channels
|
238 |
+
self.depth_separable_num_layers = depth_separable_num_layers
|
239 |
+
self.duration_predictor_flow_bins = duration_predictor_flow_bins
|
240 |
+
self.duration_predictor_tail_bound = duration_predictor_tail_bound
|
241 |
+
self.duration_predictor_kernel_size = duration_predictor_kernel_size
|
242 |
+
self.duration_predictor_dropout = duration_predictor_dropout
|
243 |
+
self.duration_predictor_num_flows = duration_predictor_num_flows
|
244 |
+
self.duration_predictor_filter_channels = duration_predictor_filter_channels
|
245 |
+
self.prior_encoder_num_flows = prior_encoder_num_flows
|
246 |
+
self.prior_encoder_num_flows_layers = prior_encoder_num_flows_layers
|
247 |
+
self.prior_encoder_num_wavenet_layers = prior_encoder_num_wavenet_layers
|
248 |
+
self.posterior_encoder_num_wavenet_layers = posterior_encoder_num_wavenet_layers
|
249 |
+
self.wavenet_kernel_size = wavenet_kernel_size
|
250 |
+
self.wavenet_dilation_rate = wavenet_dilation_rate
|
251 |
+
self.wavenet_dropout = wavenet_dropout
|
252 |
+
self.conditioning_layer_index = conditioning_layer_index
|
253 |
+
self.speaking_rate = speaking_rate
|
254 |
+
self.noise_scale = noise_scale
|
255 |
+
self.noise_scale_duration = noise_scale_duration
|
256 |
+
self.stochastic_duration_prediction_ratio = stochastic_duration_prediction_ratio
|
257 |
+
self.sampling_rate = sampling_rate
|
258 |
+
self.bert_configs = [BertConfig.from_dict(config) for config in bert_configs]
|
259 |
+
|
260 |
+
if len(upsample_kernel_sizes) != len(upsample_rates):
|
261 |
+
raise ValueError(
|
262 |
+
f"The length of `upsample_kernel_sizes` ({len(upsample_kernel_sizes)}) must match the length of "
|
263 |
+
f"`upsample_rates` ({len(upsample_rates)})"
|
264 |
+
)
|
265 |
+
|
266 |
+
super().__init__(**kwargs)
|
267 |
+
|
268 |
+
def to_dict(self):
|
269 |
+
# patch the bert_configs to be serializable
|
270 |
+
bert_configs = self.bert_configs.copy()
|
271 |
+
self.bert_configs = [config.to_dict() for config in self.bert_configs]
|
272 |
+
config_dict = super().to_dict()
|
273 |
+
self.bert_configs = bert_configs
|
274 |
+
return config_dict
|
modeling_bert_vits2.py
ADDED
@@ -0,0 +1,1674 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2023 The Kakao Enterprise Authors and the HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
"""PyTorch Bert VITS2 model."""
|
16 |
+
|
17 |
+
import math
|
18 |
+
from dataclasses import dataclass
|
19 |
+
from typing import Any, Optional, Tuple, Union, List
|
20 |
+
|
21 |
+
import numpy as np
|
22 |
+
import torch
|
23 |
+
import torch.utils.checkpoint
|
24 |
+
from torch import nn
|
25 |
+
|
26 |
+
from transformers.activations import ACT2FN
|
27 |
+
from transformers.integrations.deepspeed import is_deepspeed_zero3_enabled
|
28 |
+
from transformers.modeling_attn_mask_utils import _prepare_4d_attention_mask
|
29 |
+
from transformers.modeling_outputs import (
|
30 |
+
BaseModelOutput,
|
31 |
+
ModelOutput,
|
32 |
+
)
|
33 |
+
from transformers.models.bert.modeling_bert import BertModel
|
34 |
+
from transformers.modeling_utils import PreTrainedModel
|
35 |
+
from transformers.utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
|
36 |
+
from configuration_bert_vits2 import BertVits2Config
|
37 |
+
|
38 |
+
|
39 |
+
logger = logging.get_logger(__name__)
|
40 |
+
|
41 |
+
|
42 |
+
# General docstring
|
43 |
+
_CONFIG_FOR_DOC = "BertVits2Config"
|
44 |
+
|
45 |
+
|
46 |
+
@dataclass
|
47 |
+
class BertVits2ModelOutput(ModelOutput):
|
48 |
+
"""
|
49 |
+
Describes the outputs for the VITS model, with potential hidden states and attentions.
|
50 |
+
|
51 |
+
Args:
|
52 |
+
waveform (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
|
53 |
+
The final audio waveform predicted by the model.
|
54 |
+
sequence_lengths (`torch.FloatTensor` of shape `(batch_size,)`):
|
55 |
+
The length in samples of each element in the `waveform` batch.
|
56 |
+
spectrogram (`torch.FloatTensor` of shape `(batch_size, sequence_length, num_bins)`):
|
57 |
+
The log-mel spectrogram predicted at the output of the flow model. This spectrogram is passed to the Hi-Fi
|
58 |
+
GAN decoder model to obtain the final audio waveform.
|
59 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
60 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
61 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
62 |
+
|
63 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
64 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
65 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
66 |
+
sequence_length)`.
|
67 |
+
|
68 |
+
Attention weights after the attention softmax, used to compute the weighted average in the self-attention
|
69 |
+
heads.
|
70 |
+
"""
|
71 |
+
|
72 |
+
waveform: torch.FloatTensor = None
|
73 |
+
sequence_lengths: torch.FloatTensor = None
|
74 |
+
spectrogram: Optional[Tuple[torch.FloatTensor]] = None
|
75 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
76 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
77 |
+
|
78 |
+
|
79 |
+
@dataclass
|
80 |
+
class BertVits2TextEncoderOutput(ModelOutput):
|
81 |
+
"""
|
82 |
+
Describes the outputs for the VITS text encoder model, with potential hidden states and attentions.
|
83 |
+
|
84 |
+
Args:
|
85 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
86 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
87 |
+
prior_means (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
88 |
+
The predicted mean values of the prior distribution for the latent text variables.
|
89 |
+
prior_log_variances (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
90 |
+
The predicted log-variance values of the prior distribution for the latent text variables.
|
91 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
92 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
93 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
94 |
+
|
95 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
96 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
97 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
98 |
+
sequence_length)`.
|
99 |
+
|
100 |
+
Attention weights after the attention softmax, used to compute the weighted average in the self-attention
|
101 |
+
heads.
|
102 |
+
"""
|
103 |
+
|
104 |
+
last_hidden_state: torch.FloatTensor = None
|
105 |
+
prior_means: torch.FloatTensor = None
|
106 |
+
prior_log_variances: torch.FloatTensor = None
|
107 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
108 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
109 |
+
|
110 |
+
|
111 |
+
@torch.jit.script
|
112 |
+
def fused_add_tanh_sigmoid_multiply(input_a, input_b, num_channels):
|
113 |
+
in_act = input_a + input_b
|
114 |
+
t_act = torch.tanh(in_act[:, :num_channels, :])
|
115 |
+
s_act = torch.sigmoid(in_act[:, num_channels:, :])
|
116 |
+
acts = t_act * s_act
|
117 |
+
return acts
|
118 |
+
|
119 |
+
|
120 |
+
def _unconstrained_rational_quadratic_spline(
|
121 |
+
inputs,
|
122 |
+
unnormalized_widths,
|
123 |
+
unnormalized_heights,
|
124 |
+
unnormalized_derivatives,
|
125 |
+
reverse=False,
|
126 |
+
tail_bound=5.0,
|
127 |
+
min_bin_width=1e-3,
|
128 |
+
min_bin_height=1e-3,
|
129 |
+
min_derivative=1e-3,
|
130 |
+
):
|
131 |
+
"""
|
132 |
+
This transformation represents a monotonically increasing piecewise rational quadratic function. Outside of the
|
133 |
+
`tail_bound`, the transform behaves as an identity function.
|
134 |
+
|
135 |
+
Args:
|
136 |
+
inputs (`torch.FloatTensor` of shape `(batch_size, channels, seq_len)`:
|
137 |
+
Second half of the hidden-states input to the Vits convolutional flow module.
|
138 |
+
unnormalized_widths (`torch.FloatTensor` of shape `(batch_size, channels, seq_len, duration_predictor_flow_bins)`):
|
139 |
+
First `duration_predictor_flow_bins` of the hidden-states from the output of the convolution projection
|
140 |
+
layer in the convolutional flow module
|
141 |
+
unnormalized_heights (`torch.FloatTensor` of shape `(batch_size, channels, seq_len, duration_predictor_flow_bins)`):
|
142 |
+
Second `duration_predictor_flow_bins` of the hidden-states from the output of the convolution projection
|
143 |
+
layer in the convolutional flow module
|
144 |
+
unnormalized_derivatives (`torch.FloatTensor` of shape `(batch_size, channels, seq_len, duration_predictor_flow_bins)`):
|
145 |
+
Third `duration_predictor_flow_bins` of the hidden-states from the output of the convolution projection
|
146 |
+
layer in the convolutional flow module
|
147 |
+
reverse (`bool`, *optional*, defaults to `False`):
|
148 |
+
Whether the model is being run in reverse mode.
|
149 |
+
tail_bound (`float`, *optional* defaults to 5):
|
150 |
+
Upper and lower limit bound for the rational quadratic function. Outside of this `tail_bound`, the
|
151 |
+
transform behaves as an identity function.
|
152 |
+
min_bin_width (`float`, *optional*, defaults to 1e-3):
|
153 |
+
Minimum bin value across the width dimension for the piecewise rational quadratic function.
|
154 |
+
min_bin_height (`float`, *optional*, defaults to 1e-3):
|
155 |
+
Minimum bin value across the height dimension for the piecewise rational quadratic function.
|
156 |
+
min_derivative (`float`, *optional*, defaults to 1e-3):
|
157 |
+
Minimum bin value across the derivatives for the piecewise rational quadratic function.
|
158 |
+
Returns:
|
159 |
+
outputs (`torch.FloatTensor` of shape `(batch_size, channels, seq_len)`:
|
160 |
+
Hidden-states as transformed by the piecewise rational quadratic function with the `tail_bound` limits
|
161 |
+
applied.
|
162 |
+
log_abs_det (`torch.FloatTensor` of shape `(batch_size, channels, seq_len)`:
|
163 |
+
Logarithm of the absolute value of the determinants corresponding to the `outputs` with the `tail_bound`
|
164 |
+
limits applied.
|
165 |
+
"""
|
166 |
+
inside_interval_mask = (inputs >= -tail_bound) & (inputs <= tail_bound)
|
167 |
+
outside_interval_mask = ~inside_interval_mask
|
168 |
+
|
169 |
+
outputs = torch.zeros_like(inputs)
|
170 |
+
log_abs_det = torch.zeros_like(inputs)
|
171 |
+
constant = np.log(np.exp(1 - min_derivative) - 1)
|
172 |
+
|
173 |
+
unnormalized_derivatives = nn.functional.pad(unnormalized_derivatives, pad=(1, 1))
|
174 |
+
unnormalized_derivatives[..., 0] = constant
|
175 |
+
unnormalized_derivatives[..., -1] = constant
|
176 |
+
|
177 |
+
outputs[outside_interval_mask] = inputs[outside_interval_mask]
|
178 |
+
log_abs_det[outside_interval_mask] = 0.0
|
179 |
+
|
180 |
+
outputs[inside_interval_mask], log_abs_det[inside_interval_mask] = _rational_quadratic_spline(
|
181 |
+
inputs=inputs[inside_interval_mask],
|
182 |
+
unnormalized_widths=unnormalized_widths[inside_interval_mask, :],
|
183 |
+
unnormalized_heights=unnormalized_heights[inside_interval_mask, :],
|
184 |
+
unnormalized_derivatives=unnormalized_derivatives[inside_interval_mask, :],
|
185 |
+
reverse=reverse,
|
186 |
+
tail_bound=tail_bound,
|
187 |
+
min_bin_width=min_bin_width,
|
188 |
+
min_bin_height=min_bin_height,
|
189 |
+
min_derivative=min_derivative,
|
190 |
+
)
|
191 |
+
return outputs, log_abs_det
|
192 |
+
|
193 |
+
|
194 |
+
def _rational_quadratic_spline(
|
195 |
+
inputs,
|
196 |
+
unnormalized_widths,
|
197 |
+
unnormalized_heights,
|
198 |
+
unnormalized_derivatives,
|
199 |
+
reverse,
|
200 |
+
tail_bound,
|
201 |
+
min_bin_width,
|
202 |
+
min_bin_height,
|
203 |
+
min_derivative,
|
204 |
+
):
|
205 |
+
"""
|
206 |
+
This transformation represents a monotonically increasing piecewise rational quadratic function. Unlike the
|
207 |
+
function `_unconstrained_rational_quadratic_spline`, the function behaves the same across the `tail_bound`.
|
208 |
+
|
209 |
+
Args:
|
210 |
+
inputs (`torch.FloatTensor` of shape `(batch_size, channels, seq_len)`:
|
211 |
+
Second half of the hidden-states input to the Vits convolutional flow module.
|
212 |
+
unnormalized_widths (`torch.FloatTensor` of shape `(batch_size, channels, seq_len, duration_predictor_flow_bins)`):
|
213 |
+
First `duration_predictor_flow_bins` of the hidden-states from the output of the convolution projection
|
214 |
+
layer in the convolutional flow module
|
215 |
+
unnormalized_heights (`torch.FloatTensor` of shape `(batch_size, channels, seq_len, duration_predictor_flow_bins)`):
|
216 |
+
Second `duration_predictor_flow_bins` of the hidden-states from the output of the convolution projection
|
217 |
+
layer in the convolutional flow module
|
218 |
+
unnormalized_derivatives (`torch.FloatTensor` of shape `(batch_size, channels, seq_len, duration_predictor_flow_bins)`):
|
219 |
+
Third `duration_predictor_flow_bins` of the hidden-states from the output of the convolution projection
|
220 |
+
layer in the convolutional flow module
|
221 |
+
reverse (`bool`):
|
222 |
+
Whether the model is being run in reverse mode.
|
223 |
+
tail_bound (`float`):
|
224 |
+
Upper and lower limit bound for the rational quadratic function. Outside of this `tail_bound`, the
|
225 |
+
transform behaves as an identity function.
|
226 |
+
min_bin_width (`float`):
|
227 |
+
Minimum bin value across the width dimension for the piecewise rational quadratic function.
|
228 |
+
min_bin_height (`float`):
|
229 |
+
Minimum bin value across the height dimension for the piecewise rational quadratic function.
|
230 |
+
min_derivative (`float`):
|
231 |
+
Minimum bin value across the derivatives for the piecewise rational quadratic function.
|
232 |
+
Returns:
|
233 |
+
outputs (`torch.FloatTensor` of shape `(batch_size, channels, seq_len)`:
|
234 |
+
Hidden-states as transformed by the piecewise rational quadratic function.
|
235 |
+
log_abs_det (`torch.FloatTensor` of shape `(batch_size, channels, seq_len)`:
|
236 |
+
Logarithm of the absolute value of the determinants corresponding to the `outputs`.
|
237 |
+
"""
|
238 |
+
upper_bound = tail_bound
|
239 |
+
lower_bound = -tail_bound
|
240 |
+
|
241 |
+
if torch.min(inputs) < lower_bound or torch.max(inputs) > upper_bound:
|
242 |
+
raise ValueError("Input to a transform is not within its domain")
|
243 |
+
|
244 |
+
num_bins = unnormalized_widths.shape[-1]
|
245 |
+
|
246 |
+
if min_bin_width * num_bins > 1.0:
|
247 |
+
raise ValueError(f"Minimal bin width {min_bin_width} too large for the number of bins {num_bins}")
|
248 |
+
if min_bin_height * num_bins > 1.0:
|
249 |
+
raise ValueError(f"Minimal bin height {min_bin_height} too large for the number of bins {num_bins}")
|
250 |
+
|
251 |
+
widths = nn.functional.softmax(unnormalized_widths, dim=-1)
|
252 |
+
widths = min_bin_width + (1 - min_bin_width * num_bins) * widths
|
253 |
+
cumwidths = torch.cumsum(widths, dim=-1)
|
254 |
+
cumwidths = nn.functional.pad(cumwidths, pad=(1, 0), mode="constant", value=0.0)
|
255 |
+
cumwidths = (upper_bound - lower_bound) * cumwidths + lower_bound
|
256 |
+
cumwidths[..., 0] = lower_bound
|
257 |
+
cumwidths[..., -1] = upper_bound
|
258 |
+
widths = cumwidths[..., 1:] - cumwidths[..., :-1]
|
259 |
+
|
260 |
+
derivatives = min_derivative + nn.functional.softplus(unnormalized_derivatives)
|
261 |
+
|
262 |
+
heights = nn.functional.softmax(unnormalized_heights, dim=-1)
|
263 |
+
heights = min_bin_height + (1 - min_bin_height * num_bins) * heights
|
264 |
+
cumheights = torch.cumsum(heights, dim=-1)
|
265 |
+
cumheights = nn.functional.pad(cumheights, pad=(1, 0), mode="constant", value=0.0)
|
266 |
+
cumheights = (upper_bound - lower_bound) * cumheights + lower_bound
|
267 |
+
cumheights[..., 0] = lower_bound
|
268 |
+
cumheights[..., -1] = upper_bound
|
269 |
+
heights = cumheights[..., 1:] - cumheights[..., :-1]
|
270 |
+
|
271 |
+
bin_locations = cumheights if reverse else cumwidths
|
272 |
+
bin_locations[..., -1] += 1e-6
|
273 |
+
bin_idx = torch.sum(inputs[..., None] >= bin_locations, dim=-1) - 1
|
274 |
+
bin_idx = bin_idx[..., None]
|
275 |
+
|
276 |
+
input_cumwidths = cumwidths.gather(-1, bin_idx)[..., 0]
|
277 |
+
input_bin_widths = widths.gather(-1, bin_idx)[..., 0]
|
278 |
+
|
279 |
+
input_cumheights = cumheights.gather(-1, bin_idx)[..., 0]
|
280 |
+
delta = heights / widths
|
281 |
+
input_delta = delta.gather(-1, bin_idx)[..., 0]
|
282 |
+
|
283 |
+
input_derivatives = derivatives.gather(-1, bin_idx)[..., 0]
|
284 |
+
input_derivatives_plus_one = derivatives[..., 1:].gather(-1, bin_idx)[..., 0]
|
285 |
+
|
286 |
+
input_heights = heights.gather(-1, bin_idx)[..., 0]
|
287 |
+
|
288 |
+
intermediate1 = input_derivatives + input_derivatives_plus_one - 2 * input_delta
|
289 |
+
if not reverse:
|
290 |
+
theta = (inputs - input_cumwidths) / input_bin_widths
|
291 |
+
theta_one_minus_theta = theta * (1 - theta)
|
292 |
+
|
293 |
+
numerator = input_heights * (input_delta * theta.pow(2) + input_derivatives * theta_one_minus_theta)
|
294 |
+
denominator = input_delta + intermediate1 * theta_one_minus_theta
|
295 |
+
outputs = input_cumheights + numerator / denominator
|
296 |
+
|
297 |
+
derivative_numerator = input_delta.pow(2) * (
|
298 |
+
input_derivatives_plus_one * theta.pow(2)
|
299 |
+
+ 2 * input_delta * theta_one_minus_theta
|
300 |
+
+ input_derivatives * (1 - theta).pow(2)
|
301 |
+
)
|
302 |
+
log_abs_det = torch.log(derivative_numerator) - 2 * torch.log(denominator)
|
303 |
+
return outputs, log_abs_det
|
304 |
+
else:
|
305 |
+
# find the roots of a quadratic equation
|
306 |
+
intermediate2 = inputs - input_cumheights
|
307 |
+
intermediate3 = intermediate2 * intermediate1
|
308 |
+
a = input_heights * (input_delta - input_derivatives) + intermediate3
|
309 |
+
b = input_heights * input_derivatives - intermediate3
|
310 |
+
c = -input_delta * intermediate2
|
311 |
+
|
312 |
+
discriminant = b.pow(2) - 4 * a * c
|
313 |
+
if not (discriminant >= 0).all():
|
314 |
+
raise RuntimeError(f"invalid discriminant {discriminant}")
|
315 |
+
|
316 |
+
root = (2 * c) / (-b - torch.sqrt(discriminant))
|
317 |
+
outputs = root * input_bin_widths + input_cumwidths
|
318 |
+
|
319 |
+
theta_one_minus_theta = root * (1 - root)
|
320 |
+
denominator = input_delta + intermediate1 * theta_one_minus_theta
|
321 |
+
derivative_numerator = input_delta.pow(2) * (
|
322 |
+
input_derivatives_plus_one * root.pow(2)
|
323 |
+
+ 2 * input_delta * theta_one_minus_theta
|
324 |
+
+ input_derivatives * (1 - root).pow(2)
|
325 |
+
)
|
326 |
+
log_abs_det = torch.log(derivative_numerator) - 2 * torch.log(denominator)
|
327 |
+
return outputs, -log_abs_det
|
328 |
+
|
329 |
+
|
330 |
+
class BertVits2WaveNet(torch.nn.Module):
|
331 |
+
def __init__(self, config: BertVits2Config, num_layers: int):
|
332 |
+
super().__init__()
|
333 |
+
self.hidden_size = config.hidden_size
|
334 |
+
self.num_layers = num_layers
|
335 |
+
|
336 |
+
self.in_layers = torch.nn.ModuleList()
|
337 |
+
self.res_skip_layers = torch.nn.ModuleList()
|
338 |
+
self.dropout = nn.Dropout(config.wavenet_dropout)
|
339 |
+
|
340 |
+
# if hasattr(nn.utils.parametrizations, "weight_norm"):
|
341 |
+
# weight_norm = nn.utils.parametrizations.weight_norm
|
342 |
+
# else:
|
343 |
+
weight_norm = nn.utils.weight_norm
|
344 |
+
|
345 |
+
if config.speaker_embedding_size != 0:
|
346 |
+
cond_layer = torch.nn.Conv1d(config.speaker_embedding_size, 2 * config.hidden_size * num_layers, 1)
|
347 |
+
self.cond_layer = weight_norm(cond_layer, name="weight")
|
348 |
+
|
349 |
+
for i in range(num_layers):
|
350 |
+
dilation = config.wavenet_dilation_rate**i
|
351 |
+
padding = (config.wavenet_kernel_size * dilation - dilation) // 2
|
352 |
+
in_layer = torch.nn.Conv1d(
|
353 |
+
in_channels=config.hidden_size,
|
354 |
+
out_channels=2 * config.hidden_size,
|
355 |
+
kernel_size=config.wavenet_kernel_size,
|
356 |
+
dilation=dilation,
|
357 |
+
padding=padding,
|
358 |
+
)
|
359 |
+
in_layer = weight_norm(in_layer, name="weight")
|
360 |
+
self.in_layers.append(in_layer)
|
361 |
+
|
362 |
+
# last one is not necessary
|
363 |
+
if i < num_layers - 1:
|
364 |
+
res_skip_channels = 2 * config.hidden_size
|
365 |
+
else:
|
366 |
+
res_skip_channels = config.hidden_size
|
367 |
+
|
368 |
+
res_skip_layer = torch.nn.Conv1d(config.hidden_size, res_skip_channels, 1)
|
369 |
+
res_skip_layer = weight_norm(res_skip_layer, name="weight")
|
370 |
+
self.res_skip_layers.append(res_skip_layer)
|
371 |
+
|
372 |
+
def forward(self, inputs, padding_mask, global_conditioning=None):
|
373 |
+
outputs = torch.zeros_like(inputs)
|
374 |
+
num_channels_tensor = torch.IntTensor([self.hidden_size])
|
375 |
+
|
376 |
+
if global_conditioning is not None:
|
377 |
+
global_conditioning = self.cond_layer(global_conditioning)
|
378 |
+
|
379 |
+
for i in range(self.num_layers):
|
380 |
+
hidden_states = self.in_layers[i](inputs)
|
381 |
+
|
382 |
+
if global_conditioning is not None:
|
383 |
+
cond_offset = i * 2 * self.hidden_size
|
384 |
+
global_states = global_conditioning[:, cond_offset : cond_offset + 2 * self.hidden_size, :]
|
385 |
+
else:
|
386 |
+
global_states = torch.zeros_like(hidden_states)
|
387 |
+
|
388 |
+
acts = fused_add_tanh_sigmoid_multiply(hidden_states, global_states, num_channels_tensor[0])
|
389 |
+
acts = self.dropout(acts)
|
390 |
+
|
391 |
+
res_skip_acts = self.res_skip_layers[i](acts)
|
392 |
+
if i < self.num_layers - 1:
|
393 |
+
res_acts = res_skip_acts[:, : self.hidden_size, :]
|
394 |
+
inputs = (inputs + res_acts) * padding_mask
|
395 |
+
outputs = outputs + res_skip_acts[:, self.hidden_size :, :]
|
396 |
+
else:
|
397 |
+
outputs = outputs + res_skip_acts
|
398 |
+
|
399 |
+
return outputs * padding_mask
|
400 |
+
|
401 |
+
def remove_weight_norm(self):
|
402 |
+
if self.speaker_embedding_size != 0:
|
403 |
+
torch.nn.utils.remove_weight_norm(self.cond_layer)
|
404 |
+
for layer in self.in_layers:
|
405 |
+
torch.nn.utils.remove_weight_norm(layer)
|
406 |
+
for layer in self.res_skip_layers:
|
407 |
+
torch.nn.utils.remove_weight_norm(layer)
|
408 |
+
|
409 |
+
|
410 |
+
class BertVits2PosteriorEncoder(nn.Module):
|
411 |
+
def __init__(self, config: BertVits2Config):
|
412 |
+
super().__init__()
|
413 |
+
self.out_channels = config.flow_size
|
414 |
+
|
415 |
+
self.conv_pre = nn.Conv1d(config.spectrogram_bins, config.hidden_size, 1)
|
416 |
+
self.wavenet = BertVits2WaveNet(config, num_layers=config.posterior_encoder_num_wavenet_layers)
|
417 |
+
self.conv_proj = nn.Conv1d(config.hidden_size, self.out_channels * 2, 1)
|
418 |
+
|
419 |
+
def forward(self, inputs, padding_mask, global_conditioning=None):
|
420 |
+
inputs = self.conv_pre(inputs) * padding_mask
|
421 |
+
inputs = self.wavenet(inputs, padding_mask, global_conditioning)
|
422 |
+
stats = self.conv_proj(inputs) * padding_mask
|
423 |
+
mean, log_stddev = torch.split(stats, self.out_channels, dim=1)
|
424 |
+
sampled = (mean + torch.randn_like(mean) * torch.exp(log_stddev)) * padding_mask
|
425 |
+
return sampled, mean, log_stddev
|
426 |
+
|
427 |
+
|
428 |
+
# Copied from transformers.models.speecht5.modeling_speecht5.HifiGanResidualBlock
|
429 |
+
class HifiGanResidualBlock(nn.Module):
|
430 |
+
def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5), leaky_relu_slope=0.1):
|
431 |
+
super().__init__()
|
432 |
+
self.leaky_relu_slope = leaky_relu_slope
|
433 |
+
|
434 |
+
self.convs1 = nn.ModuleList(
|
435 |
+
[
|
436 |
+
nn.Conv1d(
|
437 |
+
channels,
|
438 |
+
channels,
|
439 |
+
kernel_size,
|
440 |
+
stride=1,
|
441 |
+
dilation=dilation[i],
|
442 |
+
padding=self.get_padding(kernel_size, dilation[i]),
|
443 |
+
)
|
444 |
+
for i in range(len(dilation))
|
445 |
+
]
|
446 |
+
)
|
447 |
+
self.convs2 = nn.ModuleList(
|
448 |
+
[
|
449 |
+
nn.Conv1d(
|
450 |
+
channels,
|
451 |
+
channels,
|
452 |
+
kernel_size,
|
453 |
+
stride=1,
|
454 |
+
dilation=1,
|
455 |
+
padding=self.get_padding(kernel_size, 1),
|
456 |
+
)
|
457 |
+
for _ in range(len(dilation))
|
458 |
+
]
|
459 |
+
)
|
460 |
+
|
461 |
+
def get_padding(self, kernel_size, dilation=1):
|
462 |
+
return (kernel_size * dilation - dilation) // 2
|
463 |
+
|
464 |
+
def apply_weight_norm(self):
|
465 |
+
for layer in self.convs1:
|
466 |
+
nn.utils.weight_norm(layer)
|
467 |
+
for layer in self.convs2:
|
468 |
+
nn.utils.weight_norm(layer)
|
469 |
+
|
470 |
+
def remove_weight_norm(self):
|
471 |
+
for layer in self.convs1:
|
472 |
+
nn.utils.remove_weight_norm(layer)
|
473 |
+
for layer in self.convs2:
|
474 |
+
nn.utils.remove_weight_norm(layer)
|
475 |
+
|
476 |
+
def forward(self, hidden_states):
|
477 |
+
for conv1, conv2 in zip(self.convs1, self.convs2):
|
478 |
+
residual = hidden_states
|
479 |
+
hidden_states = nn.functional.leaky_relu(hidden_states, self.leaky_relu_slope)
|
480 |
+
hidden_states = conv1(hidden_states)
|
481 |
+
hidden_states = nn.functional.leaky_relu(hidden_states, self.leaky_relu_slope)
|
482 |
+
hidden_states = conv2(hidden_states)
|
483 |
+
hidden_states = hidden_states + residual
|
484 |
+
return hidden_states
|
485 |
+
|
486 |
+
|
487 |
+
class BertVits2HifiGan(nn.Module):
|
488 |
+
def __init__(self, config: BertVits2Config):
|
489 |
+
super().__init__()
|
490 |
+
self.config = config
|
491 |
+
self.num_kernels = len(config.resblock_kernel_sizes)
|
492 |
+
self.num_upsamples = len(config.upsample_rates)
|
493 |
+
self.conv_pre = nn.Conv1d(
|
494 |
+
config.flow_size,
|
495 |
+
config.upsample_initial_channel,
|
496 |
+
kernel_size=7,
|
497 |
+
stride=1,
|
498 |
+
padding=3,
|
499 |
+
)
|
500 |
+
|
501 |
+
self.upsampler = nn.ModuleList()
|
502 |
+
for i, (upsample_rate, kernel_size) in enumerate(zip(config.upsample_rates, config.upsample_kernel_sizes)):
|
503 |
+
self.upsampler.append(
|
504 |
+
nn.ConvTranspose1d(
|
505 |
+
config.upsample_initial_channel // (2**i),
|
506 |
+
config.upsample_initial_channel // (2 ** (i + 1)),
|
507 |
+
kernel_size=kernel_size,
|
508 |
+
stride=upsample_rate,
|
509 |
+
padding=(kernel_size - upsample_rate) // 2,
|
510 |
+
)
|
511 |
+
)
|
512 |
+
|
513 |
+
self.resblocks = nn.ModuleList()
|
514 |
+
for i in range(len(self.upsampler)):
|
515 |
+
channels = config.upsample_initial_channel // (2 ** (i + 1))
|
516 |
+
for kernel_size, dilation in zip(config.resblock_kernel_sizes, config.resblock_dilation_sizes):
|
517 |
+
self.resblocks.append(HifiGanResidualBlock(channels, kernel_size, dilation, config.leaky_relu_slope))
|
518 |
+
|
519 |
+
self.conv_post = nn.Conv1d(channels, 1, kernel_size=7, stride=1, padding=3, bias=False)
|
520 |
+
|
521 |
+
if config.speaker_embedding_size != 0:
|
522 |
+
self.cond = nn.Conv1d(config.speaker_embedding_size, config.upsample_initial_channel, 1)
|
523 |
+
|
524 |
+
def apply_weight_norm(self):
|
525 |
+
for layer in self.upsampler:
|
526 |
+
nn.utils.weight_norm(layer)
|
527 |
+
for layer in self.resblocks:
|
528 |
+
layer.apply_weight_norm()
|
529 |
+
|
530 |
+
def remove_weight_norm(self):
|
531 |
+
for layer in self.upsampler:
|
532 |
+
nn.utils.remove_weight_norm(layer)
|
533 |
+
for layer in self.resblocks:
|
534 |
+
layer.remove_weight_norm()
|
535 |
+
|
536 |
+
def forward(
|
537 |
+
self,
|
538 |
+
spectrogram: torch.FloatTensor,
|
539 |
+
global_conditioning: Optional[torch.FloatTensor] = None
|
540 |
+
) -> torch.FloatTensor:
|
541 |
+
r"""
|
542 |
+
Converts a spectrogram into a speech waveform.
|
543 |
+
|
544 |
+
Args:
|
545 |
+
spectrogram (`torch.FloatTensor` of shape `(batch_size, config.spectrogram_bins, sequence_length)`):
|
546 |
+
Tensor containing the spectrograms.
|
547 |
+
global_conditioning (`torch.FloatTensor` of shape `(batch_size, config.speaker_embedding_size, 1)`, *optional*):
|
548 |
+
Tensor containing speaker embeddings, for multispeaker models.
|
549 |
+
|
550 |
+
Returns:
|
551 |
+
`torch.FloatTensor`: Tensor of shape shape `(batch_size, 1, num_frames)` containing the speech waveform.
|
552 |
+
"""
|
553 |
+
hidden_states = self.conv_pre(spectrogram)
|
554 |
+
|
555 |
+
if global_conditioning is not None:
|
556 |
+
hidden_states = hidden_states + self.cond(global_conditioning)
|
557 |
+
|
558 |
+
for i in range(self.num_upsamples):
|
559 |
+
hidden_states = nn.functional.leaky_relu(hidden_states, self.config.leaky_relu_slope)
|
560 |
+
hidden_states = self.upsampler[i](hidden_states)
|
561 |
+
|
562 |
+
res_state = self.resblocks[i * self.num_kernels](hidden_states)
|
563 |
+
for j in range(1, self.num_kernels):
|
564 |
+
res_state += self.resblocks[i * self.num_kernels + j](hidden_states)
|
565 |
+
hidden_states = res_state / self.num_kernels
|
566 |
+
|
567 |
+
hidden_states = nn.functional.leaky_relu(hidden_states)
|
568 |
+
hidden_states = self.conv_post(hidden_states)
|
569 |
+
waveform = torch.tanh(hidden_states)
|
570 |
+
return waveform
|
571 |
+
|
572 |
+
|
573 |
+
class BertVits2ResidualCouplingLayer(nn.Module):
|
574 |
+
def __init__(self, config: BertVits2Config):
|
575 |
+
super().__init__()
|
576 |
+
self.half_channels = config.flow_size // 2
|
577 |
+
|
578 |
+
self.conv_pre = nn.Conv1d(self.half_channels, config.hidden_size, 1)
|
579 |
+
self.wavenet = BertVits2WaveNet(config, num_layers=config.prior_encoder_num_wavenet_layers)
|
580 |
+
self.conv_post = nn.Conv1d(config.hidden_size, self.half_channels, 1)
|
581 |
+
|
582 |
+
def forward(self, inputs, padding_mask, global_conditioning=None):
|
583 |
+
first_half, second_half = torch.split(inputs, [self.half_channels] * 2, dim=1)
|
584 |
+
hidden_states = self.conv_pre(first_half) * padding_mask
|
585 |
+
hidden_states = self.wavenet(hidden_states, padding_mask, global_conditioning)
|
586 |
+
mean = self.conv_post(hidden_states) * padding_mask
|
587 |
+
log_stddev = torch.zeros_like(mean)
|
588 |
+
|
589 |
+
second_half = mean + second_half * torch.exp(log_stddev) * padding_mask
|
590 |
+
outputs = torch.cat([first_half, second_half], dim=1)
|
591 |
+
log_determinant = torch.sum(log_stddev, [1, 2])
|
592 |
+
return outputs, log_determinant
|
593 |
+
|
594 |
+
|
595 |
+
class BertVits2ResidualCouplingBlock(nn.Module):
|
596 |
+
def __init__(self, config: BertVits2Config):
|
597 |
+
super().__init__()
|
598 |
+
self.flows = nn.ModuleList()
|
599 |
+
for _ in range(config.prior_encoder_num_flows):
|
600 |
+
self.flows.append(BertVits2ResidualCouplingLayer(config))
|
601 |
+
|
602 |
+
def forward(self, inputs, padding_mask, global_conditioning=None):
|
603 |
+
x = inputs
|
604 |
+
for flow in self.flows:
|
605 |
+
x, _ = flow(x, padding_mask, global_conditioning)
|
606 |
+
x = torch.flip(x, [1])
|
607 |
+
return x
|
608 |
+
|
609 |
+
|
610 |
+
class BertVits2TransformerCouplingLayer(nn.Module):
|
611 |
+
def __init__(self, config: BertVits2Config):
|
612 |
+
super().__init__()
|
613 |
+
self.half_channels = config.flow_size // 2
|
614 |
+
|
615 |
+
self.conv_pre = nn.Conv1d(self.half_channels, config.hidden_size, 1)
|
616 |
+
self.encoder = BertVits2Encoder(
|
617 |
+
config,
|
618 |
+
kernel_size=5,
|
619 |
+
n_layers=config.prior_encoder_num_flows_layers,
|
620 |
+
)
|
621 |
+
self.conv_post = nn.Conv1d(config.hidden_size, self.half_channels, 1)
|
622 |
+
|
623 |
+
def forward(
|
624 |
+
self,
|
625 |
+
inputs,
|
626 |
+
padding_mask,
|
627 |
+
global_conditioning=None,
|
628 |
+
reverse=False,
|
629 |
+
return_dict=True,
|
630 |
+
):
|
631 |
+
inputs1, inputs2 = torch.split(inputs, [self.half_channels] * 2, 1)
|
632 |
+
hidden_state = self.conv_pre(inputs1) * padding_mask
|
633 |
+
hidden_state = self.encoder(
|
634 |
+
hidden_states=hidden_state.transpose(1, 2),
|
635 |
+
padding_mask=padding_mask.transpose(1, 2),
|
636 |
+
global_conditioning=global_conditioning,
|
637 |
+
return_dict=return_dict
|
638 |
+
)
|
639 |
+
hidden_state = hidden_state.last_hidden_state if return_dict else hidden_state[0]
|
640 |
+
hidden_state = hidden_state.transpose(1, 2)
|
641 |
+
hidden_state = self.conv_post(hidden_state) * padding_mask
|
642 |
+
logs = torch.zeros_like(hidden_state)
|
643 |
+
|
644 |
+
if not reverse:
|
645 |
+
inputs1 = hidden_state + inputs1 * torch.exp(logs) * padding_mask
|
646 |
+
x = torch.cat([inputs1, inputs2], 1)
|
647 |
+
logdet = torch.sum(logs, [1, 2])
|
648 |
+
return x, logdet
|
649 |
+
else:
|
650 |
+
inputs2 = (inputs2 - hidden_state) * torch.exp(-logs) * padding_mask
|
651 |
+
x = torch.cat([inputs1, inputs2], 1)
|
652 |
+
return x, None
|
653 |
+
|
654 |
+
|
655 |
+
class BertVits2TransformerCouplingBlock(nn.Module):
|
656 |
+
def __init__(self, config: BertVits2Config):
|
657 |
+
super().__init__()
|
658 |
+
self.flows = nn.ModuleList([
|
659 |
+
BertVits2TransformerCouplingLayer(config) for _ in range(config.prior_encoder_num_flows)
|
660 |
+
])
|
661 |
+
|
662 |
+
def forward(self, inputs, padding_mask, global_conditioning=None, reverse=False):
|
663 |
+
if not reverse:
|
664 |
+
for flow in self.flows:
|
665 |
+
inputs, _ = flow(inputs, padding_mask, global_conditioning, reverse=False)
|
666 |
+
inputs = torch.flip(inputs, [1])
|
667 |
+
else:
|
668 |
+
for flow in reversed(self.flows):
|
669 |
+
inputs = torch.flip(inputs, [1])
|
670 |
+
inputs, _ = flow(inputs, padding_mask, global_conditioning, reverse=True)
|
671 |
+
return inputs
|
672 |
+
|
673 |
+
|
674 |
+
class BertVits2DilatedDepthSeparableConv(nn.Module):
|
675 |
+
def __init__(self, config: BertVits2Config, dropout_rate=0.0):
|
676 |
+
super().__init__()
|
677 |
+
kernel_size = config.duration_predictor_kernel_size
|
678 |
+
channels = config.hidden_size
|
679 |
+
self.num_layers = config.depth_separable_num_layers
|
680 |
+
|
681 |
+
self.dropout = nn.Dropout(dropout_rate)
|
682 |
+
self.convs_dilated = nn.ModuleList()
|
683 |
+
self.convs_pointwise = nn.ModuleList()
|
684 |
+
self.norms_1 = nn.ModuleList()
|
685 |
+
self.norms_2 = nn.ModuleList()
|
686 |
+
for i in range(self.num_layers):
|
687 |
+
dilation = kernel_size**i
|
688 |
+
padding = (kernel_size * dilation - dilation) // 2
|
689 |
+
self.convs_dilated.append(
|
690 |
+
nn.Conv1d(
|
691 |
+
in_channels=channels,
|
692 |
+
out_channels=channels,
|
693 |
+
kernel_size=kernel_size,
|
694 |
+
groups=channels,
|
695 |
+
dilation=dilation,
|
696 |
+
padding=padding,
|
697 |
+
)
|
698 |
+
)
|
699 |
+
self.convs_pointwise.append(nn.Conv1d(channels, channels, 1))
|
700 |
+
self.norms_1.append(nn.LayerNorm(channels))
|
701 |
+
self.norms_2.append(nn.LayerNorm(channels))
|
702 |
+
|
703 |
+
def forward(self, inputs, padding_mask, global_conditioning=None):
|
704 |
+
if global_conditioning is not None:
|
705 |
+
inputs = inputs + global_conditioning
|
706 |
+
|
707 |
+
for i in range(self.num_layers):
|
708 |
+
hidden_states = self.convs_dilated[i](inputs * padding_mask)
|
709 |
+
hidden_states = self.norms_1[i](hidden_states.transpose(1, -1)).transpose(1, -1)
|
710 |
+
hidden_states = nn.functional.gelu(hidden_states)
|
711 |
+
hidden_states = self.convs_pointwise[i](hidden_states)
|
712 |
+
hidden_states = self.norms_2[i](hidden_states.transpose(1, -1)).transpose(1, -1)
|
713 |
+
hidden_states = nn.functional.gelu(hidden_states)
|
714 |
+
hidden_states = self.dropout(hidden_states)
|
715 |
+
inputs = inputs + hidden_states
|
716 |
+
|
717 |
+
return inputs * padding_mask
|
718 |
+
|
719 |
+
|
720 |
+
class BertVits2ConvFlow(nn.Module):
|
721 |
+
def __init__(self, config: BertVits2Config):
|
722 |
+
super().__init__()
|
723 |
+
self.filter_channels = config.hidden_size
|
724 |
+
self.half_channels = config.depth_separable_channels // 2
|
725 |
+
self.num_bins = config.duration_predictor_flow_bins
|
726 |
+
self.tail_bound = config.duration_predictor_tail_bound
|
727 |
+
|
728 |
+
self.conv_pre = nn.Conv1d(self.half_channels, self.filter_channels, 1)
|
729 |
+
self.conv_dds = BertVits2DilatedDepthSeparableConv(config)
|
730 |
+
self.conv_proj = nn.Conv1d(self.filter_channels, self.half_channels * (self.num_bins * 3 - 1), 1)
|
731 |
+
|
732 |
+
def forward(self, inputs, padding_mask, global_conditioning=None, reverse=False):
|
733 |
+
first_half, second_half = torch.split(inputs, [self.half_channels] * 2, dim=1)
|
734 |
+
|
735 |
+
hidden_states = self.conv_pre(first_half)
|
736 |
+
hidden_states = self.conv_dds(hidden_states, padding_mask, global_conditioning)
|
737 |
+
hidden_states = self.conv_proj(hidden_states) * padding_mask
|
738 |
+
|
739 |
+
batch_size, channels, length = first_half.shape
|
740 |
+
hidden_states = hidden_states.reshape(batch_size, channels, -1, length).permute(0, 1, 3, 2)
|
741 |
+
|
742 |
+
unnormalized_widths = hidden_states[..., : self.num_bins] / math.sqrt(self.filter_channels)
|
743 |
+
unnormalized_heights = hidden_states[..., self.num_bins : 2 * self.num_bins] / math.sqrt(self.filter_channels)
|
744 |
+
unnormalized_derivatives = hidden_states[..., 2 * self.num_bins :]
|
745 |
+
|
746 |
+
second_half, log_abs_det = _unconstrained_rational_quadratic_spline(
|
747 |
+
second_half,
|
748 |
+
unnormalized_widths,
|
749 |
+
unnormalized_heights,
|
750 |
+
unnormalized_derivatives,
|
751 |
+
reverse=reverse,
|
752 |
+
tail_bound=self.tail_bound,
|
753 |
+
)
|
754 |
+
|
755 |
+
outputs = torch.cat([first_half, second_half], dim=1) * padding_mask
|
756 |
+
if not reverse:
|
757 |
+
log_determinant = torch.sum(log_abs_det * padding_mask, [1, 2])
|
758 |
+
return outputs, log_determinant
|
759 |
+
else:
|
760 |
+
return outputs, None
|
761 |
+
|
762 |
+
|
763 |
+
class BertVits2ElementwiseAffine(nn.Module):
|
764 |
+
def __init__(self, config: BertVits2Config):
|
765 |
+
super().__init__()
|
766 |
+
self.channels = config.depth_separable_channels
|
767 |
+
self.translate = nn.Parameter(torch.zeros(self.channels, 1))
|
768 |
+
self.log_scale = nn.Parameter(torch.zeros(self.channels, 1))
|
769 |
+
|
770 |
+
def forward(self, inputs, padding_mask, global_conditioning=None, reverse=False):
|
771 |
+
if not reverse:
|
772 |
+
outputs = self.translate + torch.exp(self.log_scale) * inputs
|
773 |
+
outputs = outputs * padding_mask
|
774 |
+
log_determinant = torch.sum(self.log_scale * padding_mask, [1, 2])
|
775 |
+
return outputs, log_determinant
|
776 |
+
else:
|
777 |
+
outputs = (inputs - self.translate) * torch.exp(-self.log_scale) * padding_mask
|
778 |
+
return outputs, None
|
779 |
+
|
780 |
+
|
781 |
+
class BertVits2StochasticDurationPredictor(nn.Module):
|
782 |
+
def __init__(self, config):
|
783 |
+
super().__init__()
|
784 |
+
embed_dim = config.speaker_embedding_size
|
785 |
+
filter_channels = config.hidden_size
|
786 |
+
|
787 |
+
self.conv_pre = nn.Conv1d(filter_channels, filter_channels, 1)
|
788 |
+
self.conv_proj = nn.Conv1d(filter_channels, filter_channels, 1)
|
789 |
+
self.conv_dds = BertVits2DilatedDepthSeparableConv(
|
790 |
+
config,
|
791 |
+
dropout_rate=config.duration_predictor_dropout,
|
792 |
+
)
|
793 |
+
|
794 |
+
if embed_dim != 0:
|
795 |
+
self.cond = nn.Conv1d(embed_dim, filter_channels, 1)
|
796 |
+
|
797 |
+
self.flows = nn.ModuleList()
|
798 |
+
self.flows.append(BertVits2ElementwiseAffine(config))
|
799 |
+
for _ in range(config.duration_predictor_num_flows):
|
800 |
+
self.flows.append(BertVits2ConvFlow(config))
|
801 |
+
|
802 |
+
self.post_conv_pre = nn.Conv1d(1, filter_channels, 1)
|
803 |
+
self.post_conv_proj = nn.Conv1d(filter_channels, filter_channels, 1)
|
804 |
+
self.post_conv_dds = BertVits2DilatedDepthSeparableConv(
|
805 |
+
config,
|
806 |
+
dropout_rate=config.duration_predictor_dropout,
|
807 |
+
)
|
808 |
+
|
809 |
+
self.post_flows = nn.ModuleList()
|
810 |
+
self.post_flows.append(BertVits2ElementwiseAffine(config))
|
811 |
+
for _ in range(config.duration_predictor_num_flows):
|
812 |
+
self.post_flows.append(BertVits2ConvFlow(config))
|
813 |
+
|
814 |
+
def forward(self, inputs, padding_mask, global_conditioning=None, durations=None, reverse=False, noise_scale=1.0):
|
815 |
+
inputs = torch.detach(inputs)
|
816 |
+
inputs = self.conv_pre(inputs)
|
817 |
+
|
818 |
+
if global_conditioning is not None:
|
819 |
+
global_conditioning = torch.detach(global_conditioning)
|
820 |
+
inputs = inputs + self.cond(global_conditioning)
|
821 |
+
|
822 |
+
inputs = self.conv_dds(inputs, padding_mask)
|
823 |
+
inputs = self.conv_proj(inputs) * padding_mask
|
824 |
+
|
825 |
+
if not reverse:
|
826 |
+
hidden_states = self.post_conv_pre(durations)
|
827 |
+
hidden_states = self.post_conv_dds(hidden_states, padding_mask)
|
828 |
+
hidden_states = self.post_conv_proj(hidden_states) * padding_mask
|
829 |
+
|
830 |
+
random_posterior = (
|
831 |
+
torch.randn(durations.size(0), 2, durations.size(2)).to(device=inputs.device, dtype=inputs.dtype)
|
832 |
+
* padding_mask
|
833 |
+
)
|
834 |
+
log_determinant_posterior_sum = 0
|
835 |
+
latents_posterior = random_posterior
|
836 |
+
for flow in self.post_flows:
|
837 |
+
latents_posterior, log_determinant = flow(
|
838 |
+
latents_posterior, padding_mask, global_conditioning=inputs + hidden_states
|
839 |
+
)
|
840 |
+
latents_posterior = torch.flip(latents_posterior, [1])
|
841 |
+
log_determinant_posterior_sum += log_determinant
|
842 |
+
|
843 |
+
first_half, second_half = torch.split(latents_posterior, [1, 1], dim=1)
|
844 |
+
|
845 |
+
log_determinant_posterior_sum += torch.sum(
|
846 |
+
(nn.functional.logsigmoid(first_half) + nn.functional.logsigmoid(-first_half)) * padding_mask, [1, 2]
|
847 |
+
)
|
848 |
+
logq = (
|
849 |
+
torch.sum(-0.5 * (math.log(2 * math.pi) + (random_posterior**2)) * padding_mask, [1, 2])
|
850 |
+
- log_determinant_posterior_sum
|
851 |
+
)
|
852 |
+
|
853 |
+
first_half = (durations - torch.sigmoid(first_half)) * padding_mask
|
854 |
+
first_half = torch.log(torch.clamp_min(first_half, 1e-5)) * padding_mask
|
855 |
+
log_determinant_sum = torch.sum(-first_half, [1, 2])
|
856 |
+
|
857 |
+
latents = torch.cat([first_half, second_half], dim=1)
|
858 |
+
for flow in self.flows:
|
859 |
+
latents, log_determinant = flow(latents, padding_mask, global_conditioning=inputs)
|
860 |
+
latents = torch.flip(latents, [1])
|
861 |
+
log_determinant_sum += log_determinant
|
862 |
+
|
863 |
+
nll = torch.sum(0.5 * (math.log(2 * math.pi) + (latents**2)) * padding_mask, [1, 2]) - log_determinant_sum
|
864 |
+
return nll + logq
|
865 |
+
else:
|
866 |
+
flows = list(reversed(self.flows))
|
867 |
+
flows = flows[:-2] + [flows[-1]] # remove a useless vflow
|
868 |
+
|
869 |
+
latents = (
|
870 |
+
torch.randn(inputs.size(0), 2, inputs.size(2)).to(device=inputs.device, dtype=inputs.dtype)
|
871 |
+
* noise_scale
|
872 |
+
)
|
873 |
+
for flow in flows:
|
874 |
+
latents = torch.flip(latents, [1])
|
875 |
+
latents, _ = flow(latents, padding_mask, global_conditioning=inputs, reverse=True)
|
876 |
+
|
877 |
+
log_duration, _ = torch.split(latents, [1, 1], dim=1)
|
878 |
+
return log_duration
|
879 |
+
|
880 |
+
|
881 |
+
class BertVits2DurationPredictor(nn.Module):
|
882 |
+
def __init__(self, config):
|
883 |
+
super().__init__()
|
884 |
+
kernel_size = config.duration_predictor_kernel_size
|
885 |
+
filter_channels = config.duration_predictor_filter_channels
|
886 |
+
|
887 |
+
self.dropout = nn.Dropout(config.duration_predictor_dropout)
|
888 |
+
self.conv_1 = nn.Conv1d(config.hidden_size, filter_channels, kernel_size, padding=kernel_size // 2)
|
889 |
+
self.norm_1 = nn.LayerNorm(filter_channels, eps=config.layer_norm_eps)
|
890 |
+
self.conv_2 = nn.Conv1d(filter_channels, filter_channels, kernel_size, padding=kernel_size // 2)
|
891 |
+
self.norm_2 = nn.LayerNorm(filter_channels, eps=config.layer_norm_eps)
|
892 |
+
self.proj = nn.Conv1d(filter_channels, 1, 1)
|
893 |
+
|
894 |
+
if config.speaker_embedding_size != 0:
|
895 |
+
self.cond = nn.Conv1d(config.speaker_embedding_size, config.hidden_size, 1)
|
896 |
+
|
897 |
+
def forward(self, inputs, padding_mask, global_conditioning=None):
|
898 |
+
inputs = torch.detach(inputs)
|
899 |
+
|
900 |
+
if global_conditioning is not None:
|
901 |
+
global_conditioning = torch.detach(global_conditioning)
|
902 |
+
inputs = inputs + self.cond(global_conditioning)
|
903 |
+
|
904 |
+
inputs = self.conv_1(inputs * padding_mask)
|
905 |
+
inputs = torch.relu(inputs)
|
906 |
+
inputs = self.norm_1(inputs.transpose(1, -1)).transpose(1, -1)
|
907 |
+
inputs = self.dropout(inputs)
|
908 |
+
|
909 |
+
inputs = self.conv_2(inputs * padding_mask)
|
910 |
+
inputs = torch.relu(inputs)
|
911 |
+
inputs = self.norm_2(inputs.transpose(1, -1)).transpose(1, -1)
|
912 |
+
inputs = self.dropout(inputs)
|
913 |
+
|
914 |
+
inputs = self.proj(inputs * padding_mask)
|
915 |
+
return inputs * padding_mask
|
916 |
+
|
917 |
+
|
918 |
+
class BertVits2Attention(nn.Module):
|
919 |
+
"""Multi-headed attention with relative positional representation."""
|
920 |
+
|
921 |
+
def __init__(self, config: BertVits2Config):
|
922 |
+
super().__init__()
|
923 |
+
self.embed_dim = config.hidden_size
|
924 |
+
self.num_heads = config.num_attention_heads
|
925 |
+
self.dropout = config.attention_dropout
|
926 |
+
self.window_size = config.window_size
|
927 |
+
|
928 |
+
self.head_dim = self.embed_dim // self.num_heads
|
929 |
+
self.scaling = self.head_dim**-0.5
|
930 |
+
|
931 |
+
if (self.head_dim * self.num_heads) != self.embed_dim:
|
932 |
+
raise ValueError(
|
933 |
+
f"hidden_size must be divisible by num_attention_heads (got `hidden_size`: {self.embed_dim}"
|
934 |
+
f" and `num_attention_heads`: {self.num_heads})."
|
935 |
+
)
|
936 |
+
|
937 |
+
self.k_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.use_bias)
|
938 |
+
self.v_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.use_bias)
|
939 |
+
self.q_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.use_bias)
|
940 |
+
self.out_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.use_bias)
|
941 |
+
|
942 |
+
nn.init.xavier_uniform_(self.k_proj.weight)
|
943 |
+
nn.init.xavier_uniform_(self.v_proj.weight)
|
944 |
+
nn.init.xavier_uniform_(self.q_proj.weight)
|
945 |
+
|
946 |
+
if self.window_size:
|
947 |
+
self.emb_rel_k = nn.Parameter(torch.randn(1, self.window_size * 2 + 1, self.head_dim) * self.scaling)
|
948 |
+
self.emb_rel_v = nn.Parameter(torch.randn(1, self.window_size * 2 + 1, self.head_dim) * self.scaling)
|
949 |
+
|
950 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
951 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
952 |
+
|
953 |
+
def forward(
|
954 |
+
self,
|
955 |
+
hidden_states: torch.Tensor,
|
956 |
+
key_value_states: Optional[torch.Tensor] = None,
|
957 |
+
attention_mask: Optional[torch.Tensor] = None,
|
958 |
+
layer_head_mask: Optional[torch.Tensor] = None,
|
959 |
+
output_attentions: bool = False,
|
960 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
|
961 |
+
"""Input shape: Batch x Time x Channel"""
|
962 |
+
|
963 |
+
# if key_value_states are provided this layer is used as a cross-attention layer
|
964 |
+
# for the decoder
|
965 |
+
|
966 |
+
bsz, tgt_len, _ = hidden_states.size()
|
967 |
+
|
968 |
+
# get query proj
|
969 |
+
query_states = self.q_proj(hidden_states) * self.scaling
|
970 |
+
|
971 |
+
# self_attention
|
972 |
+
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
|
973 |
+
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
|
974 |
+
|
975 |
+
proj_shape = (bsz * self.num_heads, -1, self.head_dim)
|
976 |
+
query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
|
977 |
+
key_states = key_states.view(*proj_shape)
|
978 |
+
value_states = value_states.view(*proj_shape)
|
979 |
+
|
980 |
+
src_len = key_states.size(1)
|
981 |
+
attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
|
982 |
+
|
983 |
+
if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
|
984 |
+
raise ValueError(
|
985 |
+
f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
|
986 |
+
f" {attn_weights.size()}"
|
987 |
+
)
|
988 |
+
|
989 |
+
if self.window_size is not None:
|
990 |
+
key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, src_len)
|
991 |
+
relative_logits = torch.matmul(query_states, key_relative_embeddings.transpose(-2, -1))
|
992 |
+
rel_pos_bias = self._relative_position_to_absolute_position(relative_logits)
|
993 |
+
attn_weights += rel_pos_bias
|
994 |
+
|
995 |
+
if attention_mask is not None:
|
996 |
+
if attention_mask.size() != (bsz, 1, tgt_len, src_len):
|
997 |
+
raise ValueError(
|
998 |
+
f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
|
999 |
+
)
|
1000 |
+
attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
|
1001 |
+
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
|
1002 |
+
|
1003 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
|
1004 |
+
|
1005 |
+
if layer_head_mask is not None:
|
1006 |
+
if layer_head_mask.size() != (self.num_heads,):
|
1007 |
+
raise ValueError(
|
1008 |
+
f"Head mask for a single layer should be of size {(self.num_heads,)}, but is"
|
1009 |
+
f" {layer_head_mask.size()}"
|
1010 |
+
)
|
1011 |
+
attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
|
1012 |
+
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
|
1013 |
+
|
1014 |
+
if output_attentions:
|
1015 |
+
# this operation is a bit awkward, but it's required to
|
1016 |
+
# make sure that attn_weights keeps its gradient.
|
1017 |
+
# In order to do so, attn_weights have to be reshaped
|
1018 |
+
# twice and have to be reused in the following
|
1019 |
+
attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
|
1020 |
+
attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
|
1021 |
+
else:
|
1022 |
+
attn_weights_reshaped = None
|
1023 |
+
|
1024 |
+
attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
|
1025 |
+
|
1026 |
+
attn_output = torch.bmm(attn_probs, value_states)
|
1027 |
+
|
1028 |
+
if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
|
1029 |
+
raise ValueError(
|
1030 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
|
1031 |
+
f" {attn_output.size()}"
|
1032 |
+
)
|
1033 |
+
|
1034 |
+
if self.window_size is not None:
|
1035 |
+
value_relative_embeddings = self._get_relative_embeddings(self.emb_rel_v, src_len)
|
1036 |
+
relative_weights = self._absolute_position_to_relative_position(attn_probs)
|
1037 |
+
rel_pos_bias = torch.matmul(relative_weights, value_relative_embeddings)
|
1038 |
+
attn_output += rel_pos_bias
|
1039 |
+
|
1040 |
+
attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
|
1041 |
+
attn_output = attn_output.transpose(1, 2)
|
1042 |
+
|
1043 |
+
# Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
|
1044 |
+
# partitioned aross GPUs when using tensor-parallelism.
|
1045 |
+
attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
|
1046 |
+
|
1047 |
+
attn_output = self.out_proj(attn_output)
|
1048 |
+
|
1049 |
+
return attn_output, attn_weights_reshaped
|
1050 |
+
|
1051 |
+
def _get_relative_embeddings(self, relative_embeddings, length):
|
1052 |
+
pad_length = max(length - (self.window_size + 1), 0)
|
1053 |
+
if pad_length > 0:
|
1054 |
+
relative_embeddings = nn.functional.pad(relative_embeddings, [0, 0, pad_length, pad_length, 0, 0])
|
1055 |
+
|
1056 |
+
slice_start_position = max((self.window_size + 1) - length, 0)
|
1057 |
+
slice_end_position = slice_start_position + 2 * length - 1
|
1058 |
+
return relative_embeddings[:, slice_start_position:slice_end_position]
|
1059 |
+
|
1060 |
+
def _relative_position_to_absolute_position(self, x):
|
1061 |
+
batch_heads, length, _ = x.size()
|
1062 |
+
|
1063 |
+
# Concat columns of pad to shift from relative to absolute indexing.
|
1064 |
+
x = nn.functional.pad(x, [0, 1, 0, 0, 0, 0])
|
1065 |
+
|
1066 |
+
# Concat extra elements so to add up to shape (len+1, 2*len-1).
|
1067 |
+
x_flat = x.view([batch_heads, length * 2 * length])
|
1068 |
+
x_flat = nn.functional.pad(x_flat, [0, length - 1, 0, 0])
|
1069 |
+
|
1070 |
+
# Reshape and slice out the padded elements.
|
1071 |
+
x_final = x_flat.view([batch_heads, length + 1, 2 * length - 1])
|
1072 |
+
x_final = x_final[:, :length, length - 1 :]
|
1073 |
+
return x_final
|
1074 |
+
|
1075 |
+
def _absolute_position_to_relative_position(self, x):
|
1076 |
+
batch_heads, length, _ = x.size()
|
1077 |
+
|
1078 |
+
# Pad along column
|
1079 |
+
x = nn.functional.pad(x, [0, length - 1, 0, 0, 0, 0])
|
1080 |
+
x_flat = x.view([batch_heads, length * (2 * length - 1)])
|
1081 |
+
|
1082 |
+
# Add 0's in the beginning that will skew the elements after reshape
|
1083 |
+
x_flat = nn.functional.pad(x_flat, [length, 0, 0, 0])
|
1084 |
+
x_final = x_flat.view([batch_heads, length, 2 * length])[:, :, 1:]
|
1085 |
+
return x_final
|
1086 |
+
|
1087 |
+
|
1088 |
+
class BertVits2FeedForward(nn.Module):
|
1089 |
+
def __init__(self, config, kernel_size=None):
|
1090 |
+
super().__init__()
|
1091 |
+
if kernel_size is None:
|
1092 |
+
kernel_size = config.ffn_kernel_size
|
1093 |
+
self.conv_1 = nn.Conv1d(config.hidden_size, config.ffn_dim, kernel_size)
|
1094 |
+
self.conv_2 = nn.Conv1d(config.ffn_dim, config.hidden_size, kernel_size)
|
1095 |
+
self.dropout = nn.Dropout(config.activation_dropout)
|
1096 |
+
|
1097 |
+
if isinstance(config.hidden_act, str):
|
1098 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
1099 |
+
else:
|
1100 |
+
self.act_fn = config.hidden_act
|
1101 |
+
|
1102 |
+
if kernel_size > 1:
|
1103 |
+
pad_left = (kernel_size - 1) // 2
|
1104 |
+
pad_right = kernel_size // 2
|
1105 |
+
self.padding = [pad_left, pad_right, 0, 0, 0, 0]
|
1106 |
+
else:
|
1107 |
+
self.padding = None
|
1108 |
+
|
1109 |
+
def forward(self, hidden_states, padding_mask):
|
1110 |
+
hidden_states = hidden_states.permute(0, 2, 1)
|
1111 |
+
padding_mask = padding_mask.permute(0, 2, 1)
|
1112 |
+
|
1113 |
+
hidden_states = hidden_states * padding_mask
|
1114 |
+
if self.padding is not None:
|
1115 |
+
hidden_states = nn.functional.pad(hidden_states, self.padding)
|
1116 |
+
|
1117 |
+
hidden_states = self.conv_1(hidden_states)
|
1118 |
+
hidden_states = self.act_fn(hidden_states)
|
1119 |
+
hidden_states = self.dropout(hidden_states)
|
1120 |
+
|
1121 |
+
hidden_states = hidden_states * padding_mask
|
1122 |
+
if self.padding is not None:
|
1123 |
+
hidden_states = nn.functional.pad(hidden_states, self.padding)
|
1124 |
+
|
1125 |
+
hidden_states = self.conv_2(hidden_states)
|
1126 |
+
hidden_states = hidden_states * padding_mask
|
1127 |
+
|
1128 |
+
hidden_states = hidden_states.permute(0, 2, 1)
|
1129 |
+
return hidden_states
|
1130 |
+
|
1131 |
+
|
1132 |
+
class BertVits2EncoderLayer(nn.Module):
|
1133 |
+
def __init__(self, config: BertVits2Config, kernel_size=None):
|
1134 |
+
super().__init__()
|
1135 |
+
self.attention = BertVits2Attention(config)
|
1136 |
+
self.dropout = nn.Dropout(config.hidden_dropout)
|
1137 |
+
self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
1138 |
+
self.feed_forward = BertVits2FeedForward(config, kernel_size=kernel_size)
|
1139 |
+
self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
1140 |
+
|
1141 |
+
def forward(
|
1142 |
+
self,
|
1143 |
+
hidden_states: torch.Tensor,
|
1144 |
+
padding_mask: torch.FloatTensor,
|
1145 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1146 |
+
output_attentions: bool = False,
|
1147 |
+
):
|
1148 |
+
residual = hidden_states
|
1149 |
+
hidden_states, attn_weights = self.attention(
|
1150 |
+
hidden_states=hidden_states,
|
1151 |
+
attention_mask=attention_mask,
|
1152 |
+
output_attentions=output_attentions,
|
1153 |
+
)
|
1154 |
+
|
1155 |
+
hidden_states = self.dropout(hidden_states)
|
1156 |
+
hidden_states = self.layer_norm(residual + hidden_states)
|
1157 |
+
|
1158 |
+
residual = hidden_states
|
1159 |
+
hidden_states = self.feed_forward(hidden_states, padding_mask)
|
1160 |
+
hidden_states = self.dropout(hidden_states)
|
1161 |
+
hidden_states = self.final_layer_norm(residual + hidden_states)
|
1162 |
+
|
1163 |
+
outputs = (hidden_states,)
|
1164 |
+
|
1165 |
+
if output_attentions:
|
1166 |
+
outputs += (attn_weights,)
|
1167 |
+
|
1168 |
+
return outputs
|
1169 |
+
|
1170 |
+
|
1171 |
+
class BertVits2Encoder(nn.Module):
|
1172 |
+
def __init__(self, config: BertVits2Config, kernel_size=None, n_layers=None):
|
1173 |
+
super().__init__()
|
1174 |
+
self.config = config
|
1175 |
+
if n_layers is None:
|
1176 |
+
n_layers = config.num_hidden_layers
|
1177 |
+
self.speaker_embed_proj = nn.Linear(config.speaker_embedding_size, config.hidden_size)
|
1178 |
+
self.layers = nn.ModuleList([BertVits2EncoderLayer(config, kernel_size=kernel_size) for _ in range(n_layers)])
|
1179 |
+
self.gradient_checkpointing = False
|
1180 |
+
self.layerdrop = config.layerdrop
|
1181 |
+
self.conditioning_layer_index = config.conditioning_layer_index
|
1182 |
+
|
1183 |
+
def forward(
|
1184 |
+
self,
|
1185 |
+
hidden_states: torch.FloatTensor,
|
1186 |
+
padding_mask: torch.FloatTensor,
|
1187 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1188 |
+
global_conditioning: Optional[torch.Tensor] = None,
|
1189 |
+
output_attentions: Optional[bool] = None,
|
1190 |
+
output_hidden_states: Optional[bool] = None,
|
1191 |
+
return_dict: Optional[bool] = None,
|
1192 |
+
) -> Union[Tuple, BaseModelOutput]:
|
1193 |
+
all_hidden_states = () if output_hidden_states else None
|
1194 |
+
all_self_attentions = () if output_attentions else None
|
1195 |
+
|
1196 |
+
# expand attention_mask
|
1197 |
+
if attention_mask is not None:
|
1198 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
1199 |
+
attention_mask = _prepare_4d_attention_mask(attention_mask, hidden_states.dtype)
|
1200 |
+
|
1201 |
+
hidden_states = hidden_states * padding_mask
|
1202 |
+
|
1203 |
+
deepspeed_zero3_is_enabled = is_deepspeed_zero3_enabled()
|
1204 |
+
|
1205 |
+
for i, encoder_layer in enumerate(self.layers):
|
1206 |
+
if output_hidden_states:
|
1207 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
1208 |
+
|
1209 |
+
# add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
|
1210 |
+
dropout_probability = np.random.uniform(0, 1)
|
1211 |
+
|
1212 |
+
if i == self.conditioning_layer_index and global_conditioning is not None:
|
1213 |
+
global_conditioning = self.speaker_embed_proj(global_conditioning.transpose(1, 2))
|
1214 |
+
hidden_states = hidden_states + global_conditioning
|
1215 |
+
hidden_states = hidden_states * padding_mask
|
1216 |
+
|
1217 |
+
skip_the_layer = self.training and (dropout_probability < self.layerdrop)
|
1218 |
+
if not skip_the_layer or deepspeed_zero3_is_enabled:
|
1219 |
+
# under deepspeed zero3 all gpus must run in sync
|
1220 |
+
if self.gradient_checkpointing and self.training:
|
1221 |
+
layer_outputs = self._gradient_checkpointing_func(
|
1222 |
+
encoder_layer.__call__,
|
1223 |
+
hidden_states,
|
1224 |
+
padding_mask,
|
1225 |
+
attention_mask,
|
1226 |
+
output_attentions,
|
1227 |
+
)
|
1228 |
+
else:
|
1229 |
+
layer_outputs = encoder_layer(
|
1230 |
+
hidden_states,
|
1231 |
+
attention_mask=attention_mask,
|
1232 |
+
padding_mask=padding_mask,
|
1233 |
+
output_attentions=output_attentions,
|
1234 |
+
)
|
1235 |
+
hidden_states = layer_outputs[0]
|
1236 |
+
|
1237 |
+
if skip_the_layer:
|
1238 |
+
layer_outputs = (None, None)
|
1239 |
+
|
1240 |
+
if output_attentions:
|
1241 |
+
all_self_attentions = all_self_attentions + (layer_outputs[1],)
|
1242 |
+
|
1243 |
+
hidden_states = hidden_states * padding_mask
|
1244 |
+
|
1245 |
+
if output_hidden_states:
|
1246 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
1247 |
+
|
1248 |
+
if not return_dict:
|
1249 |
+
return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
|
1250 |
+
|
1251 |
+
return BaseModelOutput(
|
1252 |
+
last_hidden_state=hidden_states,
|
1253 |
+
hidden_states=all_hidden_states,
|
1254 |
+
attentions=all_self_attentions,
|
1255 |
+
)
|
1256 |
+
|
1257 |
+
|
1258 |
+
class BertVits2TextEncoder(nn.Module):
|
1259 |
+
"""
|
1260 |
+
Transformer encoder that uses relative positional representation instead of absolute positional encoding.
|
1261 |
+
"""
|
1262 |
+
|
1263 |
+
def __init__(self, config: BertVits2Config):
|
1264 |
+
super().__init__()
|
1265 |
+
self.config = config
|
1266 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, config.pad_token_id)
|
1267 |
+
nn.init.normal_(self.embed_tokens.weight, 0.0, config.hidden_size**-0.5)
|
1268 |
+
self.embed_tones = nn.Embedding(config.num_tones, config.hidden_size)
|
1269 |
+
nn.init.normal_(self.embed_tones.weight, 0.0, config.hidden_size**-0.5)
|
1270 |
+
self.embed_languages = nn.Embedding(config.num_languages, config.hidden_size)
|
1271 |
+
nn.init.normal_(self.embed_languages.weight, 0.0, config.hidden_size**-0.5)
|
1272 |
+
self.bert_projs = nn.ModuleList()
|
1273 |
+
for bert in config.bert_configs:
|
1274 |
+
self.bert_projs.append(nn.Conv1d(bert.hidden_size, config.hidden_size, 1))
|
1275 |
+
self.encoder = BertVits2Encoder(config)
|
1276 |
+
self.project = nn.Conv1d(config.hidden_size, config.flow_size * 2, kernel_size=1)
|
1277 |
+
|
1278 |
+
def get_input_embeddings(self):
|
1279 |
+
return self.embed_tokens
|
1280 |
+
|
1281 |
+
def set_input_embeddings(self, value):
|
1282 |
+
self.embed_tokens = value
|
1283 |
+
|
1284 |
+
def forward(
|
1285 |
+
self,
|
1286 |
+
input_ids: torch.Tensor,
|
1287 |
+
tone_ids: torch.Tensor,
|
1288 |
+
language_ids: torch.Tensor,
|
1289 |
+
padding_mask: torch.FloatTensor,
|
1290 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1291 |
+
bert_embeddings: Optional[List[torch.Tensor]] = None,
|
1292 |
+
global_conditioning: Optional[torch.Tensor] = None,
|
1293 |
+
output_attentions: Optional[bool] = None,
|
1294 |
+
output_hidden_states: Optional[bool] = None,
|
1295 |
+
return_dict: Optional[bool] = True,
|
1296 |
+
) -> Union[Tuple[torch.Tensor], BertVits2TextEncoderOutput]:
|
1297 |
+
x = self.embed_tokens(input_ids)
|
1298 |
+
x = x + self.embed_tones(tone_ids)
|
1299 |
+
x = x + self.embed_languages(language_ids)
|
1300 |
+
for project, inputs in zip(self.bert_projs, bert_embeddings):
|
1301 |
+
x = x + project(inputs).transpose(1, 2)
|
1302 |
+
hidden_states = x * math.sqrt(self.config.hidden_size)
|
1303 |
+
|
1304 |
+
encoder_outputs = self.encoder(
|
1305 |
+
hidden_states=hidden_states,
|
1306 |
+
padding_mask=padding_mask,
|
1307 |
+
attention_mask=attention_mask,
|
1308 |
+
global_conditioning=global_conditioning,
|
1309 |
+
output_attentions=output_attentions,
|
1310 |
+
output_hidden_states=output_hidden_states,
|
1311 |
+
return_dict=return_dict,
|
1312 |
+
)
|
1313 |
+
|
1314 |
+
last_hidden_state = encoder_outputs[0] if not return_dict else encoder_outputs.last_hidden_state
|
1315 |
+
|
1316 |
+
stats = self.project(last_hidden_state.transpose(1, 2)).transpose(1, 2) * padding_mask
|
1317 |
+
prior_means, prior_log_variances = torch.split(stats, self.config.flow_size, dim=2)
|
1318 |
+
|
1319 |
+
if not return_dict:
|
1320 |
+
outputs = (last_hidden_state, prior_means, prior_log_variances) + encoder_outputs[1:]
|
1321 |
+
return outputs
|
1322 |
+
|
1323 |
+
return BertVits2TextEncoderOutput(
|
1324 |
+
last_hidden_state=last_hidden_state,
|
1325 |
+
prior_means=prior_means,
|
1326 |
+
prior_log_variances=prior_log_variances,
|
1327 |
+
hidden_states=encoder_outputs.hidden_states,
|
1328 |
+
attentions=encoder_outputs.attentions,
|
1329 |
+
)
|
1330 |
+
|
1331 |
+
|
1332 |
+
class BertVits2ReferenceEncoder(nn.Module):
|
1333 |
+
def __init__(self, config: BertVits2Config):
|
1334 |
+
super().__init__()
|
1335 |
+
self.config = config
|
1336 |
+
ref_enc_filters = [32, 32, 64, 64, 128, 128]
|
1337 |
+
K = len(ref_enc_filters)
|
1338 |
+
filters = [1] + ref_enc_filters
|
1339 |
+
self.convs = nn.ModuleList([
|
1340 |
+
nn.utils.weight_norm(
|
1341 |
+
nn.Conv2d(
|
1342 |
+
in_channels=filters[i],
|
1343 |
+
out_channels=filters[i + 1],
|
1344 |
+
kernel_size=(3, 3),
|
1345 |
+
stride=(2, 2),
|
1346 |
+
padding=(1, 1),
|
1347 |
+
)
|
1348 |
+
)
|
1349 |
+
for i in range(K)
|
1350 |
+
])
|
1351 |
+
out_channels = self.calculate_channels(config.spectrogram_bins, 3, 2, 1, K)
|
1352 |
+
self.gru = nn.GRU(
|
1353 |
+
input_size=ref_enc_filters[-1] * out_channels,
|
1354 |
+
hidden_size=256 // 2,
|
1355 |
+
batch_first=True,
|
1356 |
+
)
|
1357 |
+
self.proj = nn.Linear(128, self.config.speaker_embedding_size)
|
1358 |
+
|
1359 |
+
def forward(self, input_ids, attention_mask):
|
1360 |
+
N = input_ids.size(0)
|
1361 |
+
out = input_ids.view(N, 1, -1, self.config.spectrogram_bins)
|
1362 |
+
for conv in self.convs:
|
1363 |
+
out = conv(out)
|
1364 |
+
# out = wn(out)
|
1365 |
+
out = nn.functional.relu(out)
|
1366 |
+
|
1367 |
+
out = out.transpose(1, 2) # [N, Ty//2^K, 128, n_mels//2^K]
|
1368 |
+
T = out.size(1)
|
1369 |
+
N = out.size(0)
|
1370 |
+
out = out.contiguous().view(N, T, -1) # [N, Ty//2^K, 128*n_mels//2^K]
|
1371 |
+
|
1372 |
+
self.gru.flatten_parameters()
|
1373 |
+
_, out = self.gru(out) # out --- [1, N, 128]
|
1374 |
+
|
1375 |
+
return self.proj(out.squeeze(0))
|
1376 |
+
|
1377 |
+
def calculate_channels(self, L, kernel_size, stride, pad, n_convs):
|
1378 |
+
for i in range(n_convs):
|
1379 |
+
L = (L - kernel_size + 2 * pad) // stride + 1
|
1380 |
+
return L
|
1381 |
+
|
1382 |
+
|
1383 |
+
class BertVits2PreTrainedModel(PreTrainedModel):
|
1384 |
+
"""
|
1385 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
1386 |
+
models.
|
1387 |
+
"""
|
1388 |
+
|
1389 |
+
config_class = BertVits2Config
|
1390 |
+
base_model_prefix = "vits"
|
1391 |
+
main_input_name = "input_ids"
|
1392 |
+
supports_gradient_checkpointing = True
|
1393 |
+
|
1394 |
+
def _init_weights(self, module):
|
1395 |
+
"""Initialize the weights"""
|
1396 |
+
if isinstance(module, nn.Linear):
|
1397 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
1398 |
+
if module.bias is not None:
|
1399 |
+
module.bias.data.zero_()
|
1400 |
+
elif isinstance(module, nn.LayerNorm):
|
1401 |
+
module.bias.data.zero_()
|
1402 |
+
module.weight.data.fill_(1.0)
|
1403 |
+
elif isinstance(module, nn.Conv1d):
|
1404 |
+
nn.init.kaiming_normal_(module.weight)
|
1405 |
+
if module.bias is not None:
|
1406 |
+
k = math.sqrt(module.groups / (module.in_channels * module.kernel_size[0]))
|
1407 |
+
nn.init.uniform_(module.bias, a=-k, b=k)
|
1408 |
+
elif isinstance(module, nn.Embedding):
|
1409 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
1410 |
+
if module.padding_idx is not None:
|
1411 |
+
module.weight.data[module.padding_idx].zero_()
|
1412 |
+
|
1413 |
+
|
1414 |
+
BERT_VITS2_START_DOCSTRING = r"""
|
1415 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
1416 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
1417 |
+
etc.)
|
1418 |
+
|
1419 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
1420 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
1421 |
+
and behavior.
|
1422 |
+
|
1423 |
+
Parameters:
|
1424 |
+
config ([`BertVits2Config`]):
|
1425 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
1426 |
+
load the weights associated with the model, only the configuration. Check out the
|
1427 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
1428 |
+
"""
|
1429 |
+
|
1430 |
+
|
1431 |
+
BERT_VITS2_INPUTS_DOCSTRING = r"""
|
1432 |
+
Args:
|
1433 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
1434 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
1435 |
+
it.
|
1436 |
+
|
1437 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
1438 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
1439 |
+
|
1440 |
+
[What are input IDs?](../glossary#input-ids)
|
1441 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1442 |
+
Mask to avoid performing convolution and attention on padding token indices. Mask values selected in `[0,
|
1443 |
+
1]`:
|
1444 |
+
|
1445 |
+
- 1 for tokens that are **not masked**,
|
1446 |
+
- 0 for tokens that are **masked**.
|
1447 |
+
|
1448 |
+
[What are attention masks?](../glossary#attention-mask)
|
1449 |
+
speaker_id (`int`, *optional*):
|
1450 |
+
Which speaker embedding to use. Only used for multispeaker models.
|
1451 |
+
output_attentions (`bool`, *optional*):
|
1452 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
1453 |
+
tensors for more detail.
|
1454 |
+
output_hidden_states (`bool`, *optional*):
|
1455 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
1456 |
+
more detail.
|
1457 |
+
return_dict (`bool`, *optional*):
|
1458 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
1459 |
+
"""
|
1460 |
+
|
1461 |
+
|
1462 |
+
@add_start_docstrings(
|
1463 |
+
"The complete VITS model, for text-to-speech synthesis.",
|
1464 |
+
BERT_VITS2_START_DOCSTRING,
|
1465 |
+
)
|
1466 |
+
class BertVits2Model(BertVits2PreTrainedModel):
|
1467 |
+
def __init__(self, config: BertVits2Config):
|
1468 |
+
super().__init__(config)
|
1469 |
+
self.config = config
|
1470 |
+
self.text_encoder = BertVits2TextEncoder(config)
|
1471 |
+
self.decoder = BertVits2HifiGan(config)
|
1472 |
+
|
1473 |
+
self.bert_encoders = nn.ModuleList([BertModel(bert_config) for bert_config in config.bert_configs])
|
1474 |
+
self.bert_proj = nn.ModuleList([nn.Linear(bert_config.hidden_size, config.hidden_size) for bert_config in config.bert_configs])
|
1475 |
+
|
1476 |
+
self.stochastic_duration_predictor = BertVits2StochasticDurationPredictor(config)
|
1477 |
+
self.duration_predictor = BertVits2DurationPredictor(config)
|
1478 |
+
|
1479 |
+
if config.num_speakers > 1:
|
1480 |
+
self.embed_speaker = nn.Embedding(config.num_speakers, config.speaker_embedding_size)
|
1481 |
+
|
1482 |
+
# This is used only for training.
|
1483 |
+
self.posterior_encoder = BertVits2PosteriorEncoder(config)
|
1484 |
+
|
1485 |
+
if config.use_transformer_flow:
|
1486 |
+
self.flow = BertVits2TransformerCouplingBlock(config)
|
1487 |
+
else:
|
1488 |
+
self.flow = BertVits2ResidualCouplingBlock(config)
|
1489 |
+
|
1490 |
+
# These parameters control the synthesised speech properties
|
1491 |
+
self.speaking_rate = config.speaking_rate
|
1492 |
+
self.noise_scale = config.noise_scale
|
1493 |
+
self.noise_scale_duration = config.noise_scale_duration
|
1494 |
+
self.stochastic_duration_prediction_ratio = config.stochastic_duration_prediction_ratio
|
1495 |
+
|
1496 |
+
# Initialize weights and apply final processing
|
1497 |
+
self.post_init()
|
1498 |
+
|
1499 |
+
def get_encoder(self):
|
1500 |
+
return self.text_encoder
|
1501 |
+
|
1502 |
+
@add_start_docstrings_to_model_forward(BERT_VITS2_INPUTS_DOCSTRING)
|
1503 |
+
@replace_return_docstrings(output_type=BertVits2ModelOutput, config_class=_CONFIG_FOR_DOC)
|
1504 |
+
def forward(
|
1505 |
+
self,
|
1506 |
+
input_ids: Optional[torch.Tensor] = None,
|
1507 |
+
tone_ids: Optional[torch.Tensor] = None,
|
1508 |
+
language_ids: Optional[torch.Tensor] = None,
|
1509 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1510 |
+
word_to_phoneme: Optional[torch.Tensor] = None,
|
1511 |
+
bert_input_ids: Optional[torch.Tensor] = None,
|
1512 |
+
bert_attention_mask: Optional[torch.Tensor] = None,
|
1513 |
+
language_id: Optional[int] = None,
|
1514 |
+
speaker_id: Optional[int] = None,
|
1515 |
+
output_attentions: Optional[bool] = None,
|
1516 |
+
output_hidden_states: Optional[bool] = None,
|
1517 |
+
return_dict: Optional[bool] = None,
|
1518 |
+
labels: Optional[torch.FloatTensor] = None,
|
1519 |
+
) -> Union[Tuple[Any], BertVits2ModelOutput]:
|
1520 |
+
r"""
|
1521 |
+
labels (`torch.FloatTensor` of shape `(batch_size, config.spectrogram_bins, sequence_length)`, *optional*):
|
1522 |
+
Float values of target spectrogram. Timesteps set to `-100.0` are ignored (masked) for the loss
|
1523 |
+
computation.
|
1524 |
+
|
1525 |
+
Returns:
|
1526 |
+
|
1527 |
+
Example:
|
1528 |
+
|
1529 |
+
```python
|
1530 |
+
>>> from transformers import BertVits2Tokenizer, BertVits2Model, set_seed
|
1531 |
+
>>> import torch
|
1532 |
+
|
1533 |
+
>>> tokenizer = BertVits2Tokenizer.from_pretrained("facebook/mms-tts-eng")
|
1534 |
+
>>> model = BertVits2Model.from_pretrained("facebook/mms-tts-eng")
|
1535 |
+
|
1536 |
+
>>> inputs = tokenizer(text="Hello - my dog is cute", return_tensors="pt")
|
1537 |
+
|
1538 |
+
>>> set_seed(555) # make deterministic
|
1539 |
+
|
1540 |
+
>>> with torch.no_grad():
|
1541 |
+
... outputs = model(inputs["input_ids"])
|
1542 |
+
>>> outputs.waveform.shape
|
1543 |
+
torch.Size([1, 45824])
|
1544 |
+
```
|
1545 |
+
"""
|
1546 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1547 |
+
output_hidden_states = (
|
1548 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
1549 |
+
)
|
1550 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1551 |
+
|
1552 |
+
batch_size = input_ids.shape[0]
|
1553 |
+
|
1554 |
+
if labels is not None:
|
1555 |
+
raise NotImplementedError("Training of VITS is not supported yet.")
|
1556 |
+
|
1557 |
+
if attention_mask is not None:
|
1558 |
+
input_padding_mask = attention_mask.unsqueeze(-1).float()
|
1559 |
+
else:
|
1560 |
+
input_padding_mask = torch.ones_like(input_ids).unsqueeze(-1).float()
|
1561 |
+
|
1562 |
+
if self.config.num_speakers > 1 and speaker_id is not None:
|
1563 |
+
if not 0 <= speaker_id < self.config.num_speakers:
|
1564 |
+
raise ValueError(f"Set `speaker_id` in the range 0-{self.config.num_speakers - 1}.")
|
1565 |
+
if isinstance(speaker_id, int):
|
1566 |
+
speaker_id = torch.full(size=(1,), fill_value=speaker_id, device=self.device)
|
1567 |
+
speaker_embeddings = self.embed_speaker(speaker_id).unsqueeze(-1)
|
1568 |
+
else:
|
1569 |
+
speaker_embeddings = None
|
1570 |
+
|
1571 |
+
if language_id is None:
|
1572 |
+
language_id = 0
|
1573 |
+
|
1574 |
+
if language_ids is None:
|
1575 |
+
language_ids = torch.full_like(input_ids, language_id)
|
1576 |
+
|
1577 |
+
phone_len = input_ids.shape[1]
|
1578 |
+
|
1579 |
+
is_tuple = isinstance(bert_input_ids, tuple)
|
1580 |
+
|
1581 |
+
bert_embeddings = [
|
1582 |
+
self.bert_features(i, bert_input_ids, bert_attention_mask, word_to_phoneme) if i == language_id and not is_tuple
|
1583 |
+
else torch.zeros(batch_size, enc.config.hidden_size, phone_len, device=self.device)
|
1584 |
+
for i, enc in enumerate(self.bert_encoders)
|
1585 |
+
]
|
1586 |
+
|
1587 |
+
text_encoder_output = self.text_encoder(
|
1588 |
+
input_ids=input_ids,
|
1589 |
+
tone_ids=tone_ids,
|
1590 |
+
language_ids=language_ids,
|
1591 |
+
padding_mask=input_padding_mask,
|
1592 |
+
attention_mask=attention_mask,
|
1593 |
+
bert_embeddings=bert_embeddings,
|
1594 |
+
global_conditioning=speaker_embeddings,
|
1595 |
+
output_attentions=output_attentions,
|
1596 |
+
output_hidden_states=output_hidden_states,
|
1597 |
+
return_dict=return_dict,
|
1598 |
+
)
|
1599 |
+
hidden_states = text_encoder_output[0] if not return_dict else text_encoder_output.last_hidden_state
|
1600 |
+
hidden_states = hidden_states.transpose(1, 2)
|
1601 |
+
input_padding_mask = input_padding_mask.transpose(1, 2)
|
1602 |
+
prior_means = text_encoder_output[1] if not return_dict else text_encoder_output.prior_means
|
1603 |
+
prior_log_variances = text_encoder_output[2] if not return_dict else text_encoder_output.prior_log_variances
|
1604 |
+
|
1605 |
+
log_duration = \
|
1606 |
+
self.stochastic_duration_predictor(
|
1607 |
+
hidden_states,
|
1608 |
+
input_padding_mask,
|
1609 |
+
global_conditioning=speaker_embeddings,
|
1610 |
+
reverse=True,
|
1611 |
+
noise_scale=self.noise_scale_duration,
|
1612 |
+
) * self.stochastic_duration_prediction_ratio + \
|
1613 |
+
self.duration_predictor(
|
1614 |
+
hidden_states,
|
1615 |
+
input_padding_mask,
|
1616 |
+
global_conditioning=speaker_embeddings
|
1617 |
+
) * (1.0 - self.stochastic_duration_prediction_ratio)
|
1618 |
+
|
1619 |
+
length_scale = 1.0 / self.speaking_rate
|
1620 |
+
duration = torch.ceil(torch.exp(log_duration) * input_padding_mask * length_scale)
|
1621 |
+
predicted_lengths = torch.clamp_min(torch.sum(duration, [1, 2]), 1).long()
|
1622 |
+
|
1623 |
+
# Create a padding mask for the output lengths of shape (batch, 1, max_output_length)
|
1624 |
+
indices = torch.arange(predicted_lengths.max(), dtype=predicted_lengths.dtype, device=predicted_lengths.device)
|
1625 |
+
output_padding_mask = indices.unsqueeze(0) < predicted_lengths.unsqueeze(1)
|
1626 |
+
output_padding_mask = output_padding_mask.unsqueeze(1).to(input_padding_mask.dtype)
|
1627 |
+
|
1628 |
+
# Reconstruct an attention tensor of shape (batch, 1, out_length, in_length)
|
1629 |
+
attn_mask = torch.unsqueeze(input_padding_mask, 2) * torch.unsqueeze(output_padding_mask, -1)
|
1630 |
+
batch_size, _, output_length, input_length = attn_mask.shape
|
1631 |
+
cum_duration = torch.cumsum(duration, -1).view(batch_size * input_length, 1)
|
1632 |
+
indices = torch.arange(output_length, dtype=duration.dtype, device=duration.device)
|
1633 |
+
valid_indices = indices.unsqueeze(0) < cum_duration
|
1634 |
+
valid_indices = valid_indices.to(attn_mask.dtype).view(batch_size, input_length, output_length)
|
1635 |
+
padded_indices = valid_indices - nn.functional.pad(valid_indices, [0, 0, 1, 0, 0, 0])[:, :-1]
|
1636 |
+
attn = padded_indices.unsqueeze(1).transpose(2, 3) * attn_mask
|
1637 |
+
|
1638 |
+
# Expand prior distribution
|
1639 |
+
prior_means = torch.matmul(attn.squeeze(1), prior_means).transpose(1, 2)
|
1640 |
+
prior_log_variances = torch.matmul(attn.squeeze(1), prior_log_variances).transpose(1, 2)
|
1641 |
+
|
1642 |
+
prior_latents = prior_means + torch.randn_like(prior_means) * torch.exp(prior_log_variances) * self.noise_scale
|
1643 |
+
latents = self.flow(prior_latents, output_padding_mask, global_conditioning=speaker_embeddings, reverse=True)
|
1644 |
+
|
1645 |
+
spectrogram = latents * output_padding_mask
|
1646 |
+
waveform = self.decoder(spectrogram, global_conditioning=speaker_embeddings)
|
1647 |
+
waveform = waveform.squeeze(1)
|
1648 |
+
sequence_lengths = predicted_lengths * np.prod(self.config.upsample_rates)
|
1649 |
+
|
1650 |
+
if not return_dict:
|
1651 |
+
outputs = (waveform, sequence_lengths, spectrogram) + text_encoder_output[3:]
|
1652 |
+
return outputs
|
1653 |
+
|
1654 |
+
return BertVits2ModelOutput(
|
1655 |
+
waveform=waveform,
|
1656 |
+
sequence_lengths=sequence_lengths,
|
1657 |
+
spectrogram=spectrogram,
|
1658 |
+
hidden_states=text_encoder_output.hidden_states,
|
1659 |
+
attentions=text_encoder_output.attentions,
|
1660 |
+
)
|
1661 |
+
|
1662 |
+
def bert_features(self, index, input_ids, attention_mask, word2phone):
|
1663 |
+
is_tuple = isinstance(input_ids, tuple)
|
1664 |
+
if is_tuple:
|
1665 |
+
input_ids = input_ids[index]
|
1666 |
+
attention_mask = attention_mask[index]
|
1667 |
+
bert_model = self.bert_encoders[index]
|
1668 |
+
features = bert_model(input_ids=input_ids, attention_mask=attention_mask, output_hidden_states=True).hidden_states
|
1669 |
+
x = torch.cat(features[-3:-2], dim=-1)
|
1670 |
+
batch_size, _, hidden_dim = x.shape
|
1671 |
+
x = x.flatten(0, 1)
|
1672 |
+
w2p_flattened = word2phone.flatten()
|
1673 |
+
phone_level_feature = x.repeat_interleave(w2p_flattened, dim=0)
|
1674 |
+
return phone_level_feature.reshape(batch_size, -1, hidden_dim).transpose(1,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|
+
# Copyright 2023 The Suno AI Authors and The HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
"""
|
16 |
+
Processor class for Bert VITS2
|
17 |
+
"""
|
18 |
+
|
19 |
+
import os
|
20 |
+
from typing import Optional, Dict
|
21 |
+
import re
|
22 |
+
|
23 |
+
from transformers.tokenization_utils_base import BatchEncoding
|
24 |
+
from transformers.processing_utils import ProcessorMixin
|
25 |
+
from transformers.utils import logging
|
26 |
+
from transformers.utils.hub import get_file_from_repo
|
27 |
+
from transformers import AutoTokenizer, PreTrainedTokenizer, TOKENIZER_MAPPING
|
28 |
+
|
29 |
+
# inject BertVits2Tokenizer
|
30 |
+
import transformers
|
31 |
+
from tokenization_bert_vits2 import BertVits2Tokenizer
|
32 |
+
transformers.BertVits2Tokenizer = BertVits2Tokenizer
|
33 |
+
TOKENIZER_MAPPING.register("bert_vits2", "BertVits2Tokenizer")
|
34 |
+
|
35 |
+
logger = logging.get_logger(__name__)
|
36 |
+
|
37 |
+
def chinese_number_to_words(text):
|
38 |
+
out = ""
|
39 |
+
if text[0] == "-":
|
40 |
+
out += "負"
|
41 |
+
text = text[1:]
|
42 |
+
elif text[0] == "+":
|
43 |
+
out += "正"
|
44 |
+
text = text[1:]
|
45 |
+
if "." in text:
|
46 |
+
integer, decimal = text.split(".")
|
47 |
+
out += chinese_number_to_words(integer)
|
48 |
+
out += "點"
|
49 |
+
for c in decimal:
|
50 |
+
out += chinese_number_to_words(c)
|
51 |
+
return out
|
52 |
+
chinese_num = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"]
|
53 |
+
length = len(text)
|
54 |
+
for i, c in enumerate(text):
|
55 |
+
if c == "0" and out[-1] not in chinese_num:
|
56 |
+
if i != length - 1 or length == 1:
|
57 |
+
out += chinese_num[0]
|
58 |
+
else:
|
59 |
+
out += chinese_num[int(c)]
|
60 |
+
if length - i == 2:
|
61 |
+
out += "十"
|
62 |
+
elif length - i == 3:
|
63 |
+
out += "百"
|
64 |
+
elif length - i == 4:
|
65 |
+
out += "千"
|
66 |
+
elif length - i == 5:
|
67 |
+
out += "萬"
|
68 |
+
elif length - i == 6:
|
69 |
+
out += "十"
|
70 |
+
elif length - i == 7:
|
71 |
+
out += "百"
|
72 |
+
elif length - i == 8:
|
73 |
+
out += "千"
|
74 |
+
elif length - i == 9:
|
75 |
+
out += "億"
|
76 |
+
elif length - i == 10:
|
77 |
+
out += "十"
|
78 |
+
elif length - i == 11:
|
79 |
+
out += "百"
|
80 |
+
elif length - i == 12:
|
81 |
+
out += "千"
|
82 |
+
elif length - i == 13:
|
83 |
+
out += "兆"
|
84 |
+
elif length - i == 14:
|
85 |
+
out += "十"
|
86 |
+
elif length - i == 15:
|
87 |
+
out += "百"
|
88 |
+
elif length - i == 16:
|
89 |
+
out += "千"
|
90 |
+
elif length - i == 17:
|
91 |
+
out += "京"
|
92 |
+
return out
|
93 |
+
|
94 |
+
|
95 |
+
class BertVits2Processor(ProcessorMixin):
|
96 |
+
r"""
|
97 |
+
Constructs a Bark processor which wraps a text tokenizer and optional Bark voice presets into a single processor.
|
98 |
+
|
99 |
+
Args:
|
100 |
+
tokenizers ([`PreTrainedTokenizer`]):
|
101 |
+
An instance of [`PreTrainedTokenizer`].
|
102 |
+
bert_tokenizer ([`PreTrainedTokenizer`]):
|
103 |
+
An instance of [`PreTrainedTokenizer`].
|
104 |
+
|
105 |
+
"""
|
106 |
+
|
107 |
+
tokenizer_class = "AutoTokenizer"
|
108 |
+
attributes = ["tokenizer"]
|
109 |
+
|
110 |
+
def __init__(self, tokenizer: PreTrainedTokenizer, bert_tokenizers: Dict[str, PreTrainedTokenizer]):
|
111 |
+
super().__init__(tokenizer)
|
112 |
+
self.__bert_tokenizers = bert_tokenizers
|
113 |
+
|
114 |
+
@property
|
115 |
+
def bert_tokenizers(self):
|
116 |
+
return self.__bert_tokenizers
|
117 |
+
|
118 |
+
def preprocess_stage1(self, text, language=None):
|
119 |
+
# normalize punctuation
|
120 |
+
text = text.replace(",", ",").replace("。", ".").replace("?", "?").replace("!", "!").replace("...", "…")
|
121 |
+
# normalize whitespace
|
122 |
+
text = re.sub(r"\s+", " ", text).strip()
|
123 |
+
# convert number to words
|
124 |
+
if language == "zh":
|
125 |
+
text = re.sub(r"[+-]?\d+", lambda x: chinese_number_to_words(x.group()), text)
|
126 |
+
return text
|
127 |
+
|
128 |
+
def preprocess_stage2(self, text, language=None):
|
129 |
+
# normalize whitespace
|
130 |
+
text = re.sub(r"\s", 'SP', text).strip()
|
131 |
+
return text
|
132 |
+
|
133 |
+
def __call__(
|
134 |
+
self,
|
135 |
+
text=None,
|
136 |
+
language=None,
|
137 |
+
return_tensors="pt",
|
138 |
+
max_length=256,
|
139 |
+
add_special_tokens=True,
|
140 |
+
return_attention_mask=True,
|
141 |
+
padding="longest",
|
142 |
+
**kwargs,
|
143 |
+
):
|
144 |
+
"""
|
145 |
+
Main method to prepare for the model one or several sequences(s). This method forwards the `text` and `kwargs`
|
146 |
+
arguments to the AutoTokenizer's [`~AutoTokenizer.__call__`] to encode the text. The method also proposes a
|
147 |
+
voice preset which is a dictionary of arrays that conditions `Bark`'s output. `kwargs` arguments are forwarded
|
148 |
+
to the tokenizer and to `cached_file` method if `voice_preset` is a valid filename.
|
149 |
+
|
150 |
+
Args:
|
151 |
+
text (`str`, `List[str]`, `List[List[str]]`):
|
152 |
+
The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
|
153 |
+
(pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
|
154 |
+
`is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
|
155 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
156 |
+
If set, will return tensors of a particular framework. Acceptable values are:
|
157 |
+
|
158 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
159 |
+
- `'np'`: Return NumPy `np.ndarray` objects.
|
160 |
+
|
161 |
+
Returns:
|
162 |
+
Tuple([`BatchEncoding`], [`BatchFeature`]): A tuple composed of a [`BatchEncoding`], i.e the output of the
|
163 |
+
`tokenizer` and a [`BatchFeature`], i.e the voice preset with the right tensors type.
|
164 |
+
"""
|
165 |
+
|
166 |
+
if language is None:
|
167 |
+
raise ValueError("The language argument is required for BertVits2Processor.")
|
168 |
+
|
169 |
+
if language not in self.bert_tokenizers:
|
170 |
+
raise ValueError(f"Language '{language}' not supported by BertVits2Processor.")
|
171 |
+
|
172 |
+
bert_text = self.preprocess_stage1(text, language)
|
173 |
+
g2p_text = self.preprocess_stage2(bert_text, language)
|
174 |
+
|
175 |
+
phone_text, tone_ids, lang_ids, word2ph = self.tokenizer.convert_g2p(g2p_text, language, add_special_tokens)
|
176 |
+
|
177 |
+
encoded_text = self.tokenizer(
|
178 |
+
phone_text,
|
179 |
+
return_tensors=return_tensors,
|
180 |
+
padding=padding,
|
181 |
+
max_length=max_length,
|
182 |
+
return_attention_mask=return_attention_mask,
|
183 |
+
**kwargs,
|
184 |
+
)
|
185 |
+
|
186 |
+
bert_tokenizer = self.bert_tokenizers[language]
|
187 |
+
bert_encoded_text = bert_tokenizer(
|
188 |
+
bert_text,
|
189 |
+
return_tensors=return_tensors,
|
190 |
+
padding=padding,
|
191 |
+
max_length=max_length,
|
192 |
+
return_attention_mask=return_attention_mask,
|
193 |
+
add_special_tokens=add_special_tokens,
|
194 |
+
return_token_type_ids=False,
|
195 |
+
**kwargs,
|
196 |
+
)
|
197 |
+
|
198 |
+
return BatchEncoding({
|
199 |
+
**encoded_text,
|
200 |
+
**{ f"bert_{k}": v for k, v in bert_encoded_text.items() },
|
201 |
+
"tone_ids": [tone_ids],
|
202 |
+
"language_ids": [lang_ids],
|
203 |
+
"word_to_phoneme": [word2ph],
|
204 |
+
}, tensor_type=return_tensors)
|
205 |
+
|
206 |
+
@classmethod
|
207 |
+
def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
|
208 |
+
args = cls._get_arguments_from_pretrained(pretrained_model_name_or_path, **kwargs)
|
209 |
+
processor_dict, kwargs = cls.get_processor_dict(pretrained_model_name_or_path, **kwargs)
|
210 |
+
processor_dict['bert_tokenizers'] = {
|
211 |
+
key: AutoTokenizer.from_pretrained(pretrained_model_name_or_path, subfolder=val)
|
212 |
+
for key, val in processor_dict['bert_tokenizers'].items()
|
213 |
+
}
|
214 |
+
return cls.from_args_and_dict(args, processor_dict, **kwargs)
|
215 |
+
|
216 |
+
def save_pretrained(
|
217 |
+
self,
|
218 |
+
save_directory,
|
219 |
+
**kwargs,
|
220 |
+
):
|
221 |
+
"""
|
222 |
+
Save the processor to the `save_directory` directory. If the processor has been created from a
|
223 |
+
repository, the method will push the model to the `save_directory` repository.
|
224 |
+
|
225 |
+
Args:
|
226 |
+
save_directory (`str`):
|
227 |
+
Directory where the processor will be saved.
|
228 |
+
push_to_hub (`bool`, `optional`, defaults to `False`):
|
229 |
+
Whether or not to push the model to the Hugging Face Hub after saving it.
|
230 |
+
kwargs:
|
231 |
+
Additional attributes to be saved with the processor.
|
232 |
+
"""
|
233 |
+
os.makedirs(save_directory, exist_ok=True)
|
234 |
+
for language, tokenizer in self.bert_tokenizers.items():
|
235 |
+
tokenizer.save_pretrained(os.path.join(save_directory, f"bert_{language}"))
|
236 |
+
bert_tokenizers = self.bert_tokenizers
|
237 |
+
self.bert_tokenizers = {language: f"bert_{language}" for language in self.bert_tokenizers}
|
238 |
+
outputs = super().save_pretrained(save_directory, **kwargs)
|
239 |
+
self.bert_tokenizers = bert_tokenizers
|
240 |
+
return outputs
|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kakao Enterprise Authors, the MMS-TTS Authors and the HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
"""Tokenization class for VITS."""
|
16 |
+
|
17 |
+
import json
|
18 |
+
import os
|
19 |
+
import re
|
20 |
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
21 |
+
|
22 |
+
from transformers.tokenization_utils import PreTrainedTokenizer
|
23 |
+
from transformers.utils import is_phonemizer_available, logging
|
24 |
+
|
25 |
+
|
26 |
+
if is_phonemizer_available():
|
27 |
+
import phonemizer
|
28 |
+
|
29 |
+
|
30 |
+
logger = logging.get_logger(__name__)
|
31 |
+
|
32 |
+
VOCAB_FILES_NAMES = {
|
33 |
+
"vocab_file": "vocab.json",
|
34 |
+
}
|
35 |
+
|
36 |
+
def is_symbol(ch):
|
37 |
+
return ch in "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
|
38 |
+
|
39 |
+
class BertVits2Tokenizer(PreTrainedTokenizer):
|
40 |
+
"""
|
41 |
+
Construct a VITS tokenizer. Also supports MMS-TTS.
|
42 |
+
|
43 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
|
44 |
+
this superclass for more information regarding those methods.
|
45 |
+
|
46 |
+
Args:
|
47 |
+
vocab_file (`str`):
|
48 |
+
Path to the vocabulary file.
|
49 |
+
language (`str`, *optional*):
|
50 |
+
Language identifier.
|
51 |
+
add_blank (`bool`, *optional*, defaults to `True`):
|
52 |
+
Whether to insert token id 0 in between the other tokens.
|
53 |
+
normalize (`bool`, *optional*, defaults to `True`):
|
54 |
+
Whether to normalize the input text by removing all casing and punctuation.
|
55 |
+
phonemize (`bool`, *optional*, defaults to `True`):
|
56 |
+
Whether to convert the input text into phonemes.
|
57 |
+
is_uroman (`bool`, *optional*, defaults to `False`):
|
58 |
+
Whether the `uroman` Romanizer needs to be applied to the input text prior to tokenizing.
|
59 |
+
"""
|
60 |
+
|
61 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
62 |
+
model_input_names = [
|
63 |
+
"input_ids",
|
64 |
+
# "input_tones",
|
65 |
+
"attention_mask",
|
66 |
+
]
|
67 |
+
|
68 |
+
def __init__(
|
69 |
+
self,
|
70 |
+
vocab_file,
|
71 |
+
pad_token="<pad>",
|
72 |
+
unk_token="<unk>",
|
73 |
+
space_token=None,
|
74 |
+
languages=None,
|
75 |
+
add_blank=True,
|
76 |
+
**kwargs,
|
77 |
+
) -> None:
|
78 |
+
with open(vocab_file, encoding="utf-8") as vocab_handle:
|
79 |
+
self.encoder = json.load(vocab_handle)
|
80 |
+
|
81 |
+
self.decoder = {v: k for k, v in self.encoder.items()}
|
82 |
+
self.languages = languages
|
83 |
+
self.add_blank = add_blank
|
84 |
+
|
85 |
+
super().__init__(
|
86 |
+
pad_token=pad_token,
|
87 |
+
unk_token=unk_token,
|
88 |
+
space_token=space_token,
|
89 |
+
languages=languages,
|
90 |
+
add_blank=add_blank,
|
91 |
+
**kwargs,
|
92 |
+
)
|
93 |
+
|
94 |
+
@property
|
95 |
+
def vocab_size(self):
|
96 |
+
return len(self.encoder)
|
97 |
+
|
98 |
+
def get_vocab(self):
|
99 |
+
vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
|
100 |
+
vocab.update(self.added_tokens_encoder)
|
101 |
+
return vocab
|
102 |
+
|
103 |
+
def zh_g2p(self, text: str) -> Tuple[str, List[int], List[int]]:
|
104 |
+
"""Converts a string of Chinese text into a list of phonemes and tones."""
|
105 |
+
from pypinyin import lazy_pinyin, Style
|
106 |
+
|
107 |
+
with open(os.path.join(os.path.dirname(__file__), "data", "zh_g2p.json"), encoding="utf-8") as f:
|
108 |
+
g2p = json.load(f)
|
109 |
+
|
110 |
+
phones = []
|
111 |
+
tones = []
|
112 |
+
word2ph = []
|
113 |
+
|
114 |
+
initials = lazy_pinyin(text, neutral_tone_with_five=True, style=Style.INITIALS, tone_sandhi=True)
|
115 |
+
finals = lazy_pinyin(text, neutral_tone_with_five=True, style=Style.FINALS_TONE3, tone_sandhi=True)
|
116 |
+
|
117 |
+
for initial, final in zip(initials, finals):
|
118 |
+
tone = 0
|
119 |
+
if final[-1].isdigit():
|
120 |
+
pinyin = initial + final[:-1]
|
121 |
+
tone = int(final[-1])
|
122 |
+
if initial:
|
123 |
+
pinyin = re.sub(r"uei$", "ui", pinyin)
|
124 |
+
pinyin = re.sub(r"iou$", "iu", pinyin)
|
125 |
+
pinyin = re.sub(r"uen$", "un", pinyin)
|
126 |
+
else:
|
127 |
+
pinyin = re.sub(r"^ing$", "ying", pinyin)
|
128 |
+
pinyin = re.sub(r"^i$", "yi", pinyin)
|
129 |
+
pinyin = re.sub(r"^in$", "yin", pinyin)
|
130 |
+
pinyin = re.sub(r"^u$", "wu", pinyin)
|
131 |
+
pinyin = re.sub(r"^v", "yu", pinyin)
|
132 |
+
pinyin = re.sub(r"^e", "e", pinyin)
|
133 |
+
pinyin = re.sub(r"^i", "y", pinyin)
|
134 |
+
pinyin = re.sub(r"^u", "w", pinyin)
|
135 |
+
else:
|
136 |
+
pinyin = initial + final
|
137 |
+
if initial == final:
|
138 |
+
tone = 0
|
139 |
+
phone = [initial]
|
140 |
+
else:
|
141 |
+
phone = g2p.get(pinyin, [self.unk_token])
|
142 |
+
if phone[0] == self.unk_token:
|
143 |
+
tone = 0
|
144 |
+
phone = [self.unk_token]
|
145 |
+
tones += [tone] * len(phone)
|
146 |
+
phones += phone
|
147 |
+
if initial != 'SP':
|
148 |
+
word2ph.append(len(phone))
|
149 |
+
else:
|
150 |
+
word2ph[-1] += 1
|
151 |
+
|
152 |
+
phones = "<|SEP|>".join(phones)
|
153 |
+
return phones, tones, word2ph
|
154 |
+
|
155 |
+
|
156 |
+
def convert_g2p(self, text: str, language: str, add_special_tokens: bool) -> Tuple[str, List[int], List[int]]:
|
157 |
+
"""Converts a string of text into a list of phonemes and tones."""
|
158 |
+
if not is_phonemizer_available():
|
159 |
+
raise ImportError("Phonemizer is not available. Please install it using `pip install phonemizer`.")
|
160 |
+
|
161 |
+
if language.startswith("zh"):
|
162 |
+
phones, tones, word2ph = self.zh_g2p(text)
|
163 |
+
else:
|
164 |
+
raise ValueError(f"Language '{language}' not supported by VITS.")
|
165 |
+
|
166 |
+
lang_ids = [self.languages.index(language)] * len(tones)
|
167 |
+
|
168 |
+
if self.add_blank:
|
169 |
+
tones = self._add_blank(tones, 0)
|
170 |
+
lang_ids = self._add_blank(lang_ids, 0)
|
171 |
+
|
172 |
+
for i in range(len(word2ph)):
|
173 |
+
word2ph[i] = word2ph[i] * 2
|
174 |
+
word2ph[0] += 1
|
175 |
+
|
176 |
+
if add_special_tokens:
|
177 |
+
word2ph = [0] + word2ph + [0]
|
178 |
+
|
179 |
+
return phones, tones, lang_ids, word2ph
|
180 |
+
|
181 |
+
def _add_blank(self, sequence: List[Union[str, int]], blank: Union[str, int]) -> List[Union[str, int]]:
|
182 |
+
interspersed = [blank] * (len(sequence) * 2 + 1)
|
183 |
+
interspersed[1::2] = sequence
|
184 |
+
return interspersed
|
185 |
+
|
186 |
+
def _tokenize(self, text: str) -> List[str]:
|
187 |
+
"""Tokenize a string by inserting the `<pad>` token at the boundary between adjacent characters."""
|
188 |
+
tokens = []
|
189 |
+
|
190 |
+
if '<|SEP|>' in text:
|
191 |
+
tokens = text.split('<|SEP|>')
|
192 |
+
else: # fallback
|
193 |
+
i = 0
|
194 |
+
while i < len(text):
|
195 |
+
found = False
|
196 |
+
for j in range(min(len(text), i + 2), i, -1):
|
197 |
+
subtext = text[i:j]
|
198 |
+
if subtext in self.encoder:
|
199 |
+
tokens.append(subtext)
|
200 |
+
i = j
|
201 |
+
found = True
|
202 |
+
break
|
203 |
+
if not found:
|
204 |
+
tokens.append(self.unk_token)
|
205 |
+
i += 1
|
206 |
+
|
207 |
+
if self.add_blank:
|
208 |
+
tokens = self._add_blank(tokens, self.pad_token)
|
209 |
+
|
210 |
+
return tokens
|
211 |
+
|
212 |
+
def convert_tokens_to_string(self, tokens: List[str]) -> str:
|
213 |
+
if self.add_blank and len(tokens) > 1:
|
214 |
+
tokens = tokens[1::2]
|
215 |
+
return "".join(tokens)
|
216 |
+
|
217 |
+
def _convert_token_to_id(self, token):
|
218 |
+
"""Converts a token (str) in an id using the vocab."""
|
219 |
+
return self.encoder.get(token, self.encoder.get(self.unk_token))
|
220 |
+
|
221 |
+
def _convert_id_to_token(self, index):
|
222 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
223 |
+
return self.decoder.get(index)
|
224 |
+
|
225 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Union[Tuple[str], None]:
|
226 |
+
if not os.path.isdir(save_directory):
|
227 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
228 |
+
return
|
229 |
+
|
230 |
+
vocab_file = os.path.join(
|
231 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
232 |
+
)
|
233 |
+
|
234 |
+
with open(vocab_file, "w", encoding="utf-8") as f:
|
235 |
+
f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
|
236 |
+
|
237 |
+
return (vocab_file,)
|