try L2 kv
Browse files- .gitattributes +1 -0
- Modules/vits/models.py +163 -470
- Utils/text_utils.py +2 -1
- api.py +5 -14
- audiocraft/builders.py +11 -12
- audiocraft/transformer.py +20 -8
- demo.py +2 -2
- msinference.py +31 -21
.gitattributes
CHANGED
|
@@ -47,3 +47,4 @@ uc_spk_Landscape2Soundscape_Masterpieces_pics/03_Schinkel_WS200-002.jpg filter=l
|
|
| 47 |
uc_spk_Landscape2Soundscape_Masterpieces_pics/11_Liebermann_NG4-94_001.jpg filter=lfs diff=lfs merge=lfs -text
|
| 48 |
uc_spk_Landscape2Soundscape_Masterpieces_pics/12_Slevogt_AII1022_001.jpg filter=lfs diff=lfs merge=lfs -text
|
| 49 |
assets/audiobook_TTS.docx filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 47 |
uc_spk_Landscape2Soundscape_Masterpieces_pics/11_Liebermann_NG4-94_001.jpg filter=lfs diff=lfs merge=lfs -text
|
| 48 |
uc_spk_Landscape2Soundscape_Masterpieces_pics/12_Slevogt_AII1022_001.jpg filter=lfs diff=lfs merge=lfs -text
|
| 49 |
assets/audiobook_TTS.docx filter=lfs diff=lfs merge=lfs -text
|
| 50 |
+
assets/ocr.jpg filter=lfs diff=lfs merge=lfs -text
|
Modules/vits/models.py
CHANGED
|
@@ -5,136 +5,13 @@ import numpy as np
|
|
| 5 |
import torch
|
| 6 |
import torch.utils.checkpoint
|
| 7 |
from torch import nn
|
| 8 |
-
|
| 9 |
from transformers.modeling_attn_mask_utils import _prepare_4d_attention_mask
|
| 10 |
from transformers.modeling_outputs import BaseModelOutput, ModelOutput
|
| 11 |
from transformers.modeling_utils import PreTrainedModel
|
| 12 |
from transformers.configuration_utils import PretrainedConfig
|
| 13 |
|
| 14 |
class VitsConfig(PretrainedConfig):
|
| 15 |
-
r"""
|
| 16 |
-
This is the configuration class to store the configuration of a [`VitsModel`]. It is used to instantiate a VITS
|
| 17 |
-
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
| 18 |
-
defaults will yield a similar configuration to that of the VITS
|
| 19 |
-
[facebook/mms-tts-eng](https://huggingface.co/facebook/mms-tts-eng) architecture.
|
| 20 |
-
|
| 21 |
-
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 22 |
-
documentation from [`PretrainedConfig`] for more information.
|
| 23 |
-
|
| 24 |
-
Args:
|
| 25 |
-
vocab_size (`int`, *optional*, defaults to 38):
|
| 26 |
-
Vocabulary size of the VITS model. Defines the number of different tokens that can be represented by the
|
| 27 |
-
`inputs_ids` passed to the forward method of [`VitsModel`].
|
| 28 |
-
hidden_size (`int`, *optional*, defaults to 192):
|
| 29 |
-
Dimensionality of the text encoder layers.
|
| 30 |
-
num_hidden_layers (`int`, *optional*, defaults to 6):
|
| 31 |
-
Number of hidden layers in the Transformer encoder.
|
| 32 |
-
num_attention_heads (`int`, *optional*, defaults to 2):
|
| 33 |
-
Number of attention heads for each attention layer in the Transformer encoder.
|
| 34 |
-
window_size (`int`, *optional*, defaults to 4):
|
| 35 |
-
Window size for the relative positional embeddings in the attention layers of the Transformer encoder.
|
| 36 |
-
use_bias (`bool`, *optional*, defaults to `True`):
|
| 37 |
-
Whether to use bias in the key, query, value projection layers in the Transformer encoder.
|
| 38 |
-
ffn_dim (`int`, *optional*, defaults to 768):
|
| 39 |
-
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
| 40 |
-
layerdrop (`float`, *optional*, defaults to 0.1):
|
| 41 |
-
The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
|
| 42 |
-
for more details.
|
| 43 |
-
ffn_kernel_size (`int`, *optional*, defaults to 3):
|
| 44 |
-
Kernel size of the 1D convolution layers used by the feed-forward network in the Transformer encoder.
|
| 45 |
-
flow_size (`int`, *optional*, defaults to 192):
|
| 46 |
-
Dimensionality of the flow layers.
|
| 47 |
-
spectrogram_bins (`int`, *optional*, defaults to 513):
|
| 48 |
-
Number of frequency bins in the target spectrogram.
|
| 49 |
-
hidden_act (`str` or `function`, *optional*, defaults to `"relu"`):
|
| 50 |
-
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 51 |
-
`"relu"`, `"selu"` and `"gelu_new"` are supported.
|
| 52 |
-
hidden_dropout (`float`, *optional*, defaults to 0.1):
|
| 53 |
-
The dropout probability for all fully connected layers in the embeddings and encoder.
|
| 54 |
-
attention_dropout (`float`, *optional*, defaults to 0.1):
|
| 55 |
-
The dropout ratio for the attention probabilities.
|
| 56 |
-
activation_dropout (`float`, *optional*, defaults to 0.1):
|
| 57 |
-
The dropout ratio for activations inside the fully connected layer.
|
| 58 |
-
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 59 |
-
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 60 |
-
layer_norm_eps (`float`, *optional*, defaults to 1e-05):
|
| 61 |
-
The epsilon used by the layer normalization layers.
|
| 62 |
-
use_stochastic_duration_prediction (`bool`, *optional*, defaults to `True`):
|
| 63 |
-
Whether to use the stochastic duration prediction module or the regular duration predictor.
|
| 64 |
-
num_speakers (`int`, *optional*, defaults to 1):
|
| 65 |
-
Number of speakers if this is a multi-speaker model.
|
| 66 |
-
speaker_embedding_size (`int`, *optional*, defaults to 0):
|
| 67 |
-
Number of channels used by the speaker embeddings. Is zero for single-speaker models.
|
| 68 |
-
upsample_initial_channel (`int`, *optional*, defaults to 512):
|
| 69 |
-
The number of input channels into the HiFi-GAN upsampling network.
|
| 70 |
-
upsample_rates (`Tuple[int]` or `List[int]`, *optional*, defaults to `[8, 8, 2, 2]`):
|
| 71 |
-
A tuple of integers defining the stride of each 1D convolutional layer in the HiFi-GAN upsampling network.
|
| 72 |
-
The length of `upsample_rates` defines the number of convolutional layers and has to match the length of
|
| 73 |
-
`upsample_kernel_sizes`.
|
| 74 |
-
upsample_kernel_sizes (`Tuple[int]` or `List[int]`, *optional*, defaults to `[16, 16, 4, 4]`):
|
| 75 |
-
A tuple of integers defining the kernel size of each 1D convolutional layer in the HiFi-GAN upsampling
|
| 76 |
-
network. The length of `upsample_kernel_sizes` defines the number of convolutional layers and has to match
|
| 77 |
-
the length of `upsample_rates`.
|
| 78 |
-
resblock_kernel_sizes (`Tuple[int]` or `List[int]`, *optional*, defaults to `[3, 7, 11]`):
|
| 79 |
-
A tuple of integers defining the kernel sizes of the 1D convolutional layers in the HiFi-GAN
|
| 80 |
-
multi-receptive field fusion (MRF) module.
|
| 81 |
-
resblock_dilation_sizes (`Tuple[Tuple[int]]` or `List[List[int]]`, *optional*, defaults to `[[1, 3, 5], [1, 3, 5], [1, 3, 5]]`):
|
| 82 |
-
A nested tuple of integers defining the dilation rates of the dilated 1D convolutional layers in the
|
| 83 |
-
HiFi-GAN multi-receptive field fusion (MRF) module.
|
| 84 |
-
leaky_relu_slope (`float`, *optional*, defaults to 0.1):
|
| 85 |
-
The angle of the negative slope used by the leaky ReLU activation.
|
| 86 |
-
depth_separable_channels (`int`, *optional*, defaults to 2):
|
| 87 |
-
Number of channels to use in each depth-separable block.
|
| 88 |
-
depth_separable_num_layers (`int`, *optional*, defaults to 3):
|
| 89 |
-
Number of convolutional layers to use in each depth-separable block.
|
| 90 |
-
duration_predictor_flow_bins (`int`, *optional*, defaults to 10):
|
| 91 |
-
Number of channels to map using the unonstrained rational spline in the duration predictor model.
|
| 92 |
-
duration_predictor_tail_bound (`float`, *optional*, defaults to 5.0):
|
| 93 |
-
Value of the tail bin boundary when computing the unconstrained rational spline in the duration predictor
|
| 94 |
-
model.
|
| 95 |
-
duration_predictor_kernel_size (`int`, *optional*, defaults to 3):
|
| 96 |
-
Kernel size of the 1D convolution layers used in the duration predictor model.
|
| 97 |
-
duration_predictor_dropout (`float`, *optional*, defaults to 0.5):
|
| 98 |
-
The dropout ratio for the duration predictor model.
|
| 99 |
-
duration_predictor_num_flows (`int`, *optional*, defaults to 4):
|
| 100 |
-
Number of flow stages used by the duration predictor model.
|
| 101 |
-
duration_predictor_filter_channels (`int`, *optional*, defaults to 256):
|
| 102 |
-
Number of channels for the convolution layers used in the duration predictor model.
|
| 103 |
-
prior_encoder_num_flows (`int`, *optional*, defaults to 4):
|
| 104 |
-
Number of flow stages used by the prior encoder flow model.
|
| 105 |
-
prior_encoder_num_wavenet_layers (`int`, *optional*, defaults to 4):
|
| 106 |
-
Number of WaveNet layers used by the prior encoder flow model.
|
| 107 |
-
posterior_encoder_num_wavenet_layers (`int`, *optional*, defaults to 16):
|
| 108 |
-
Number of WaveNet layers used by the posterior encoder model.
|
| 109 |
-
wavenet_kernel_size (`int`, *optional*, defaults to 5):
|
| 110 |
-
Kernel size of the 1D convolution layers used in the WaveNet model.
|
| 111 |
-
wavenet_dilation_rate (`int`, *optional*, defaults to 1):
|
| 112 |
-
Dilation rates of the dilated 1D convolutional layers used in the WaveNet model.
|
| 113 |
-
wavenet_dropout (`float`, *optional*, defaults to 0.0):
|
| 114 |
-
The dropout ratio for the WaveNet layers.
|
| 115 |
-
speaking_rate (`float`, *optional*, defaults to 1.0):
|
| 116 |
-
Speaking rate. Larger values give faster synthesised speech.
|
| 117 |
-
noise_scale (`float`, *optional*, defaults to 0.667):
|
| 118 |
-
How random the speech prediction is. Larger values create more variation in the predicted speech.
|
| 119 |
-
noise_scale_duration (`float`, *optional*, defaults to 0.8):
|
| 120 |
-
How random the duration prediction is. Larger values create more variation in the predicted durations.
|
| 121 |
-
sampling_rate (`int`, *optional*, defaults to 16000):
|
| 122 |
-
The sampling rate at which the output audio waveform is digitalized expressed in hertz (Hz).
|
| 123 |
-
|
| 124 |
-
Example:
|
| 125 |
-
|
| 126 |
-
```python
|
| 127 |
-
>>> from transformers import VitsModel, VitsConfig
|
| 128 |
-
|
| 129 |
-
>>> # Initializing a "facebook/mms-tts-eng" style configuration
|
| 130 |
-
>>> configuration = VitsConfig()
|
| 131 |
-
|
| 132 |
-
>>> # Initializing a model (with random weights) from the "facebook/mms-tts-eng" style configuration
|
| 133 |
-
>>> model = VitsModel(configuration)
|
| 134 |
-
|
| 135 |
-
>>> # Accessing the model configuration
|
| 136 |
-
>>> configuration = model.config
|
| 137 |
-
```"""
|
| 138 |
|
| 139 |
model_type = "vits"
|
| 140 |
|
|
@@ -151,7 +28,7 @@ class VitsConfig(PretrainedConfig):
|
|
| 151 |
ffn_kernel_size=3,
|
| 152 |
flow_size=192,
|
| 153 |
spectrogram_bins=513,
|
| 154 |
-
hidden_act="relu",
|
| 155 |
hidden_dropout=0.1,
|
| 156 |
attention_dropout=0.1,
|
| 157 |
activation_dropout=0.1,
|
|
@@ -180,7 +57,7 @@ class VitsConfig(PretrainedConfig):
|
|
| 180 |
wavenet_kernel_size=5,
|
| 181 |
wavenet_dilation_rate=1,
|
| 182 |
wavenet_dropout=0.0,
|
| 183 |
-
speaking_rate=1.0,
|
| 184 |
noise_scale=0.667,
|
| 185 |
noise_scale_duration=0.8,
|
| 186 |
sampling_rate=16_000,
|
|
@@ -197,10 +74,8 @@ class VitsConfig(PretrainedConfig):
|
|
| 197 |
self.ffn_kernel_size = ffn_kernel_size
|
| 198 |
self.flow_size = flow_size
|
| 199 |
self.spectrogram_bins = spectrogram_bins
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
self.attention_dropout = attention_dropout
|
| 203 |
-
self.activation_dropout = activation_dropout
|
| 204 |
self.initializer_range = initializer_range
|
| 205 |
self.layer_norm_eps = layer_norm_eps
|
| 206 |
self.use_stochastic_duration_prediction = use_stochastic_duration_prediction
|
|
@@ -217,7 +92,7 @@ class VitsConfig(PretrainedConfig):
|
|
| 217 |
self.duration_predictor_flow_bins = duration_predictor_flow_bins
|
| 218 |
self.duration_predictor_tail_bound = duration_predictor_tail_bound
|
| 219 |
self.duration_predictor_kernel_size = duration_predictor_kernel_size
|
| 220 |
-
|
| 221 |
self.duration_predictor_num_flows = duration_predictor_num_flows
|
| 222 |
self.duration_predictor_filter_channels = duration_predictor_filter_channels
|
| 223 |
self.prior_encoder_num_flows = prior_encoder_num_flows
|
|
@@ -225,8 +100,8 @@ class VitsConfig(PretrainedConfig):
|
|
| 225 |
self.posterior_encoder_num_wavenet_layers = posterior_encoder_num_wavenet_layers
|
| 226 |
self.wavenet_kernel_size = wavenet_kernel_size
|
| 227 |
self.wavenet_dilation_rate = wavenet_dilation_rate
|
| 228 |
-
|
| 229 |
-
|
| 230 |
self.noise_scale = noise_scale
|
| 231 |
self.noise_scale_duration = noise_scale_duration
|
| 232 |
self.sampling_rate = sampling_rate
|
|
@@ -241,50 +116,14 @@ class VitsConfig(PretrainedConfig):
|
|
| 241 |
|
| 242 |
|
| 243 |
|
| 244 |
-
|
| 245 |
-
# ============================ modeling
|
| 246 |
-
|
| 247 |
@dataclass
|
| 248 |
class VitsTextEncoderOutput(ModelOutput):
|
| 249 |
-
"""
|
| 250 |
-
Describes the outputs for the VITS text encoder model, with potential hidden states and attentions.
|
| 251 |
-
|
| 252 |
-
Args:
|
| 253 |
-
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 254 |
-
Sequence of hidden-states at the output of the last layer of the model.
|
| 255 |
-
prior_means (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 256 |
-
The predicted mean values of the prior distribution for the latent text variables.
|
| 257 |
-
prior_log_variances (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 258 |
-
The predicted log-variance values of the prior distribution for the latent text variables.
|
| 259 |
-
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 260 |
-
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
| 261 |
-
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
| 262 |
-
|
| 263 |
-
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
| 264 |
-
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 265 |
-
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 266 |
-
sequence_length)`.
|
| 267 |
-
|
| 268 |
-
Attention weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 269 |
-
heads.
|
| 270 |
-
"""
|
| 271 |
-
|
| 272 |
last_hidden_state: torch.FloatTensor = None
|
| 273 |
prior_means: torch.FloatTensor = None
|
| 274 |
prior_log_variances: torch.FloatTensor = None
|
| 275 |
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
| 276 |
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
| 277 |
|
| 278 |
-
|
| 279 |
-
@torch.jit.script
|
| 280 |
-
def fused_add_tanh_sigmoid_multiply(input_a, input_b, num_channels):
|
| 281 |
-
in_act = input_a + input_b
|
| 282 |
-
t_act = torch.tanh(in_act[:, :num_channels, :])
|
| 283 |
-
s_act = torch.sigmoid(in_act[:, num_channels:, :])
|
| 284 |
-
acts = t_act * s_act
|
| 285 |
-
return acts
|
| 286 |
-
|
| 287 |
-
|
| 288 |
def _unconstrained_rational_quadratic_spline(
|
| 289 |
inputs,
|
| 290 |
unnormalized_widths,
|
|
@@ -296,46 +135,11 @@ def _unconstrained_rational_quadratic_spline(
|
|
| 296 |
min_bin_height=1e-3,
|
| 297 |
min_derivative=1e-3,
|
| 298 |
):
|
| 299 |
-
"""
|
| 300 |
-
This transformation represents a monotonically increasing piecewise rational quadratic function. Outside of the
|
| 301 |
-
`tail_bound`, the transform behaves as an identity function.
|
| 302 |
-
|
| 303 |
-
Args:
|
| 304 |
-
inputs (`torch.FloatTensor` of shape `(batch_size, channels, seq_len)`:
|
| 305 |
-
Second half of the hidden-states input to the Vits convolutional flow module.
|
| 306 |
-
unnormalized_widths (`torch.FloatTensor` of shape `(batch_size, channels, seq_len, duration_predictor_flow_bins)`):
|
| 307 |
-
First `duration_predictor_flow_bins` of the hidden-states from the output of the convolution projection
|
| 308 |
-
layer in the convolutional flow module
|
| 309 |
-
unnormalized_heights (`torch.FloatTensor` of shape `(batch_size, channels, seq_len, duration_predictor_flow_bins)`):
|
| 310 |
-
Second `duration_predictor_flow_bins` of the hidden-states from the output of the convolution projection
|
| 311 |
-
layer in the convolutional flow module
|
| 312 |
-
unnormalized_derivatives (`torch.FloatTensor` of shape `(batch_size, channels, seq_len, duration_predictor_flow_bins)`):
|
| 313 |
-
Third `duration_predictor_flow_bins` of the hidden-states from the output of the convolution projection
|
| 314 |
-
layer in the convolutional flow module
|
| 315 |
-
reverse (`bool`, *optional*, defaults to `False`):
|
| 316 |
-
Whether the model is being run in reverse mode.
|
| 317 |
-
tail_bound (`float`, *optional* defaults to 5):
|
| 318 |
-
Upper and lower limit bound for the rational quadratic function. Outside of this `tail_bound`, the
|
| 319 |
-
transform behaves as an identity function.
|
| 320 |
-
min_bin_width (`float`, *optional*, defaults to 1e-3):
|
| 321 |
-
Minimum bin value across the width dimension for the piecewise rational quadratic function.
|
| 322 |
-
min_bin_height (`float`, *optional*, defaults to 1e-3):
|
| 323 |
-
Minimum bin value across the height dimension for the piecewise rational quadratic function.
|
| 324 |
-
min_derivative (`float`, *optional*, defaults to 1e-3):
|
| 325 |
-
Minimum bin value across the derivatives for the piecewise rational quadratic function.
|
| 326 |
-
Returns:
|
| 327 |
-
outputs (`torch.FloatTensor` of shape `(batch_size, channels, seq_len)`:
|
| 328 |
-
Hidden-states as transformed by the piecewise rational quadratic function with the `tail_bound` limits
|
| 329 |
-
applied.
|
| 330 |
-
log_abs_det (`torch.FloatTensor` of shape `(batch_size, channels, seq_len)`:
|
| 331 |
-
Logarithm of the absolute value of the determinants corresponding to the `outputs` with the `tail_bound`
|
| 332 |
-
limits applied.
|
| 333 |
-
"""
|
| 334 |
inside_interval_mask = (inputs >= -tail_bound) & (inputs <= tail_bound)
|
| 335 |
outside_interval_mask = ~inside_interval_mask
|
| 336 |
|
| 337 |
outputs = torch.zeros_like(inputs)
|
| 338 |
-
|
| 339 |
constant = np.log(np.exp(1 - min_derivative) - 1)
|
| 340 |
|
| 341 |
unnormalized_derivatives = nn.functional.pad(unnormalized_derivatives, pad=(1, 1))
|
|
@@ -343,9 +147,9 @@ def _unconstrained_rational_quadratic_spline(
|
|
| 343 |
unnormalized_derivatives[..., -1] = constant
|
| 344 |
|
| 345 |
outputs[outside_interval_mask] = inputs[outside_interval_mask]
|
| 346 |
-
|
| 347 |
|
| 348 |
-
outputs[inside_interval_mask]
|
| 349 |
inputs=inputs[inside_interval_mask],
|
| 350 |
unnormalized_widths=unnormalized_widths[inside_interval_mask, :],
|
| 351 |
unnormalized_heights=unnormalized_heights[inside_interval_mask, :],
|
|
@@ -356,7 +160,7 @@ def _unconstrained_rational_quadratic_spline(
|
|
| 356 |
min_bin_height=min_bin_height,
|
| 357 |
min_derivative=min_derivative,
|
| 358 |
)
|
| 359 |
-
return outputs
|
| 360 |
|
| 361 |
|
| 362 |
def _rational_quadratic_spline(
|
|
@@ -455,20 +259,21 @@ def _rational_quadratic_spline(
|
|
| 455 |
|
| 456 |
intermediate1 = input_derivatives + input_derivatives_plus_one - 2 * input_delta
|
| 457 |
if not reverse:
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
)
|
| 470 |
-
|
| 471 |
-
|
|
|
|
| 472 |
else:
|
| 473 |
# find the roots of a quadratic equation
|
| 474 |
intermediate2 = inputs - input_cumheights
|
|
@@ -484,26 +289,26 @@ def _rational_quadratic_spline(
|
|
| 484 |
root = (2 * c) / (-b - torch.sqrt(discriminant))
|
| 485 |
outputs = root * input_bin_widths + input_cumwidths
|
| 486 |
|
| 487 |
-
theta_one_minus_theta = root * (1 - root)
|
| 488 |
-
denominator = input_delta + intermediate1 * theta_one_minus_theta
|
| 489 |
-
derivative_numerator = input_delta.pow(2) * (
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
)
|
| 494 |
-
log_abs_det = torch.log(derivative_numerator) - 2 * torch.log(denominator)
|
| 495 |
-
return outputs
|
| 496 |
|
| 497 |
|
| 498 |
class VitsWaveNet(torch.nn.Module):
|
| 499 |
-
def __init__(self, config
|
| 500 |
super().__init__()
|
| 501 |
self.hidden_size = config.hidden_size
|
| 502 |
self.num_layers = num_layers
|
| 503 |
|
| 504 |
self.in_layers = torch.nn.ModuleList()
|
| 505 |
self.res_skip_layers = torch.nn.ModuleList()
|
| 506 |
-
|
| 507 |
|
| 508 |
if hasattr(nn.utils.parametrizations, "weight_norm"):
|
| 509 |
weight_norm = nn.utils.parametrizations.weight_norm
|
|
@@ -539,22 +344,28 @@ class VitsWaveNet(torch.nn.Module):
|
|
| 539 |
|
| 540 |
def forward(self, inputs, padding_mask, global_conditioning=None):
|
| 541 |
outputs = torch.zeros_like(inputs)
|
| 542 |
-
|
| 543 |
|
| 544 |
-
if global_conditioning is not None:
|
| 545 |
-
global_conditioning = self.cond_layer(global_conditioning)
|
| 546 |
|
| 547 |
for i in range(self.num_layers):
|
| 548 |
-
|
| 549 |
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
global_states = global_conditioning[:, cond_offset : cond_offset + 2 * self.hidden_size, :]
|
| 553 |
-
else:
|
| 554 |
-
global_states = torch.zeros_like(hidden_states)
|
| 555 |
|
| 556 |
-
acts = fused_add_tanh_sigmoid_multiply(hidden_states, global_states, num_channels_tensor[0])
|
| 557 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 558 |
|
| 559 |
res_skip_acts = self.res_skip_layers[i](acts)
|
| 560 |
if i < self.num_layers - 1:
|
|
@@ -642,7 +453,7 @@ class HifiGanResidualBlock(nn.Module):
|
|
| 642 |
|
| 643 |
|
| 644 |
class VitsHifiGan(nn.Module):
|
| 645 |
-
def __init__(self, config
|
| 646 |
super().__init__()
|
| 647 |
self.config = config
|
| 648 |
self.num_kernels = len(config.resblock_kernel_sizes)
|
|
@@ -695,25 +506,12 @@ class VitsHifiGan(nn.Module):
|
|
| 695 |
layer.remove_weight_norm()
|
| 696 |
|
| 697 |
def forward(
|
| 698 |
-
self,
|
| 699 |
-
|
| 700 |
-
|
| 701 |
-
|
| 702 |
-
|
| 703 |
-
Args:
|
| 704 |
-
spectrogram (`torch.FloatTensor` of shape `(batch_size, config.spectrogram_bins, sequence_length)`):
|
| 705 |
-
Tensor containing the spectrograms.
|
| 706 |
-
global_conditioning (`torch.FloatTensor` of shape `(batch_size, config.speaker_embedding_size, 1)`, *optional*):
|
| 707 |
-
Tensor containing speaker embeddings, for multispeaker models.
|
| 708 |
-
|
| 709 |
-
Returns:
|
| 710 |
-
`torch.FloatTensor`: Tensor of shape shape `(batch_size, 1, num_frames)` containing the speech waveform.
|
| 711 |
-
"""
|
| 712 |
hidden_states = self.conv_pre(spectrogram)
|
| 713 |
|
| 714 |
-
if global_conditioning is not None:
|
| 715 |
-
hidden_states = hidden_states + self.cond(global_conditioning)
|
| 716 |
-
|
| 717 |
for i in range(self.num_upsamples):
|
| 718 |
hidden_states = nn.functional.leaky_relu(hidden_states, self.config.leaky_relu_slope)
|
| 719 |
hidden_states = self.upsampler[i](hidden_states)
|
|
@@ -730,7 +528,7 @@ class VitsHifiGan(nn.Module):
|
|
| 730 |
|
| 731 |
|
| 732 |
class VitsResidualCouplingLayer(nn.Module):
|
| 733 |
-
def __init__(self, config
|
| 734 |
super().__init__()
|
| 735 |
self.half_channels = config.flow_size // 2
|
| 736 |
|
|
@@ -757,7 +555,7 @@ class VitsResidualCouplingLayer(nn.Module):
|
|
| 757 |
|
| 758 |
|
| 759 |
class VitsResidualCouplingBlock(nn.Module):
|
| 760 |
-
def __init__(self, config
|
| 761 |
super().__init__()
|
| 762 |
self.flows = nn.ModuleList()
|
| 763 |
for _ in range(config.prior_encoder_num_flows):
|
|
@@ -776,13 +574,12 @@ class VitsResidualCouplingBlock(nn.Module):
|
|
| 776 |
|
| 777 |
|
| 778 |
class VitsDilatedDepthSeparableConv(nn.Module):
|
| 779 |
-
def __init__(self, config
|
| 780 |
super().__init__()
|
| 781 |
kernel_size = config.duration_predictor_kernel_size
|
| 782 |
channels = config.hidden_size
|
| 783 |
self.num_layers = config.depth_separable_num_layers
|
| 784 |
|
| 785 |
-
self.dropout = nn.Dropout(dropout_rate)
|
| 786 |
self.convs_dilated = nn.ModuleList()
|
| 787 |
self.convs_pointwise = nn.ModuleList()
|
| 788 |
self.norms_1 = nn.ModuleList()
|
|
@@ -815,14 +612,14 @@ class VitsDilatedDepthSeparableConv(nn.Module):
|
|
| 815 |
hidden_states = self.convs_pointwise[i](hidden_states)
|
| 816 |
hidden_states = self.norms_2[i](hidden_states.transpose(1, -1)).transpose(1, -1)
|
| 817 |
hidden_states = nn.functional.gelu(hidden_states)
|
| 818 |
-
|
| 819 |
inputs = inputs + hidden_states
|
| 820 |
|
| 821 |
return inputs * padding_mask
|
| 822 |
|
| 823 |
|
| 824 |
class VitsConvFlow(nn.Module):
|
| 825 |
-
def __init__(self, config
|
| 826 |
super().__init__()
|
| 827 |
self.filter_channels = config.hidden_size
|
| 828 |
self.half_channels = config.depth_separable_channels // 2
|
|
@@ -847,7 +644,7 @@ class VitsConvFlow(nn.Module):
|
|
| 847 |
unnormalized_heights = hidden_states[..., self.num_bins : 2 * self.num_bins] / math.sqrt(self.filter_channels)
|
| 848 |
unnormalized_derivatives = hidden_states[..., 2 * self.num_bins :]
|
| 849 |
|
| 850 |
-
second_half
|
| 851 |
second_half,
|
| 852 |
unnormalized_widths,
|
| 853 |
unnormalized_heights,
|
|
@@ -857,11 +654,8 @@ class VitsConvFlow(nn.Module):
|
|
| 857 |
)
|
| 858 |
|
| 859 |
outputs = torch.cat([first_half, second_half], dim=1) * padding_mask
|
| 860 |
-
|
| 861 |
-
|
| 862 |
-
return outputs, log_determinant
|
| 863 |
-
else:
|
| 864 |
-
return outputs, None
|
| 865 |
|
| 866 |
|
| 867 |
class VitsElementwiseAffine(nn.Module):
|
|
@@ -873,10 +667,11 @@ class VitsElementwiseAffine(nn.Module):
|
|
| 873 |
|
| 874 |
def forward(self, inputs, padding_mask, global_conditioning=None, reverse=False):
|
| 875 |
if not reverse:
|
| 876 |
-
|
| 877 |
-
outputs =
|
| 878 |
-
|
| 879 |
-
|
|
|
|
| 880 |
else:
|
| 881 |
outputs = (inputs - self.translate) * torch.exp(-self.log_scale) * padding_mask
|
| 882 |
return outputs, None
|
|
@@ -890,10 +685,7 @@ class VitsStochasticDurationPredictor(nn.Module):
|
|
| 890 |
|
| 891 |
self.conv_pre = nn.Conv1d(filter_channels, filter_channels, 1)
|
| 892 |
self.conv_proj = nn.Conv1d(filter_channels, filter_channels, 1)
|
| 893 |
-
self.conv_dds = VitsDilatedDepthSeparableConv(
|
| 894 |
-
config,
|
| 895 |
-
dropout_rate=config.duration_predictor_dropout,
|
| 896 |
-
)
|
| 897 |
|
| 898 |
if embed_dim != 0:
|
| 899 |
self.cond = nn.Conv1d(embed_dim, filter_channels, 1)
|
|
@@ -903,69 +695,71 @@ class VitsStochasticDurationPredictor(nn.Module):
|
|
| 903 |
for _ in range(config.duration_predictor_num_flows):
|
| 904 |
self.flows.append(VitsConvFlow(config))
|
| 905 |
|
| 906 |
-
self.post_conv_pre = nn.Conv1d(1, filter_channels, 1)
|
| 907 |
-
self.post_conv_proj = nn.Conv1d(filter_channels, filter_channels, 1)
|
| 908 |
-
self.post_conv_dds = VitsDilatedDepthSeparableConv(
|
| 909 |
-
|
| 910 |
-
|
| 911 |
-
)
|
| 912 |
|
| 913 |
-
self.post_flows = nn.ModuleList()
|
| 914 |
-
self.post_flows.append(VitsElementwiseAffine(config))
|
| 915 |
-
for _ in range(config.duration_predictor_num_flows):
|
| 916 |
-
|
| 917 |
|
| 918 |
def forward(self, inputs, padding_mask, global_conditioning=None, durations=None, reverse=False, noise_scale=1.0):
|
| 919 |
inputs = torch.detach(inputs)
|
| 920 |
inputs = self.conv_pre(inputs)
|
| 921 |
|
| 922 |
if global_conditioning is not None:
|
| 923 |
-
|
| 924 |
-
|
|
|
|
| 925 |
|
| 926 |
inputs = self.conv_dds(inputs, padding_mask)
|
| 927 |
inputs = self.conv_proj(inputs) * padding_mask
|
| 928 |
|
| 929 |
if not reverse:
|
| 930 |
-
|
| 931 |
-
hidden_states = self.
|
| 932 |
-
hidden_states = self.
|
| 933 |
-
|
| 934 |
-
|
| 935 |
-
|
| 936 |
-
|
| 937 |
-
|
| 938 |
-
|
| 939 |
-
|
| 940 |
-
|
| 941 |
-
|
| 942 |
-
|
| 943 |
-
|
| 944 |
-
|
| 945 |
-
|
| 946 |
-
|
| 947 |
-
|
| 948 |
-
|
| 949 |
-
|
| 950 |
-
|
| 951 |
-
)
|
| 952 |
-
|
| 953 |
-
|
| 954 |
-
|
| 955 |
-
|
| 956 |
-
|
| 957 |
-
|
| 958 |
-
first_half =
|
| 959 |
-
|
| 960 |
-
|
| 961 |
-
|
| 962 |
-
|
| 963 |
-
|
| 964 |
-
|
| 965 |
-
|
| 966 |
-
|
| 967 |
-
|
| 968 |
-
|
|
|
|
| 969 |
else:
|
| 970 |
flows = list(reversed(self.flows))
|
| 971 |
flows = flows[:-2] + [flows[-1]] # remove a useless vflow
|
|
@@ -982,51 +776,17 @@ class VitsStochasticDurationPredictor(nn.Module):
|
|
| 982 |
return log_duration
|
| 983 |
|
| 984 |
|
| 985 |
-
class VitsDurationPredictor(nn.Module):
|
| 986 |
-
def __init__(self, config):
|
| 987 |
-
super().__init__()
|
| 988 |
-
kernel_size = config.duration_predictor_kernel_size
|
| 989 |
-
filter_channels = config.duration_predictor_filter_channels
|
| 990 |
-
|
| 991 |
-
self.dropout = nn.Dropout(config.duration_predictor_dropout)
|
| 992 |
-
self.conv_1 = nn.Conv1d(config.hidden_size, filter_channels, kernel_size, padding=kernel_size // 2)
|
| 993 |
-
self.norm_1 = nn.LayerNorm(filter_channels, eps=config.layer_norm_eps)
|
| 994 |
-
self.conv_2 = nn.Conv1d(filter_channels, filter_channels, kernel_size, padding=kernel_size // 2)
|
| 995 |
-
self.norm_2 = nn.LayerNorm(filter_channels, eps=config.layer_norm_eps)
|
| 996 |
-
self.proj = nn.Conv1d(filter_channels, 1, 1)
|
| 997 |
-
|
| 998 |
-
if config.speaker_embedding_size != 0:
|
| 999 |
-
self.cond = nn.Conv1d(config.speaker_embedding_size, config.hidden_size, 1)
|
| 1000 |
-
|
| 1001 |
-
def forward(self, inputs, padding_mask, global_conditioning=None):
|
| 1002 |
-
inputs = torch.detach(inputs)
|
| 1003 |
-
|
| 1004 |
-
if global_conditioning is not None:
|
| 1005 |
-
global_conditioning = torch.detach(global_conditioning)
|
| 1006 |
-
inputs = inputs + self.cond(global_conditioning)
|
| 1007 |
|
| 1008 |
-
inputs = self.conv_1(inputs * padding_mask)
|
| 1009 |
-
inputs = torch.relu(inputs)
|
| 1010 |
-
inputs = self.norm_1(inputs.transpose(1, -1)).transpose(1, -1)
|
| 1011 |
-
inputs = self.dropout(inputs)
|
| 1012 |
-
|
| 1013 |
-
inputs = self.conv_2(inputs * padding_mask)
|
| 1014 |
-
inputs = torch.relu(inputs)
|
| 1015 |
-
inputs = self.norm_2(inputs.transpose(1, -1)).transpose(1, -1)
|
| 1016 |
-
inputs = self.dropout(inputs)
|
| 1017 |
-
|
| 1018 |
-
inputs = self.proj(inputs * padding_mask)
|
| 1019 |
-
return inputs * padding_mask
|
| 1020 |
|
| 1021 |
|
| 1022 |
class VitsAttention(nn.Module):
|
| 1023 |
"""Multi-headed attention with relative positional representation."""
|
| 1024 |
|
| 1025 |
-
def __init__(self, config
|
| 1026 |
super().__init__()
|
| 1027 |
self.embed_dim = config.hidden_size
|
| 1028 |
self.num_heads = config.num_attention_heads
|
| 1029 |
-
|
| 1030 |
self.window_size = config.window_size
|
| 1031 |
|
| 1032 |
self.head_dim = self.embed_dim // self.num_heads
|
|
@@ -1044,10 +804,11 @@ class VitsAttention(nn.Module):
|
|
| 1044 |
self.out_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.use_bias)
|
| 1045 |
|
| 1046 |
if self.window_size:
|
|
|
|
| 1047 |
self.emb_rel_k = nn.Parameter(torch.randn(1, self.window_size * 2 + 1, self.head_dim) * self.scaling)
|
| 1048 |
self.emb_rel_v = nn.Parameter(torch.randn(1, self.window_size * 2 + 1, self.head_dim) * self.scaling)
|
| 1049 |
|
| 1050 |
-
def _shape(self, tensor
|
| 1051 |
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
| 1052 |
|
| 1053 |
def forward(
|
|
@@ -1080,55 +841,32 @@ class VitsAttention(nn.Module):
|
|
| 1080 |
src_len = key_states.size(1)
|
| 1081 |
attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
|
| 1082 |
|
| 1083 |
-
|
| 1084 |
-
raise ValueError(
|
| 1085 |
-
f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
|
| 1086 |
-
f" {attn_weights.size()}"
|
| 1087 |
-
)
|
| 1088 |
|
| 1089 |
if self.window_size is not None:
|
| 1090 |
# 4
|
| 1091 |
-
key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, src_len)
|
|
|
|
|
|
|
| 1092 |
relative_logits = torch.matmul(query_states, key_relative_embeddings.transpose(-2, -1))
|
|
|
|
| 1093 |
rel_pos_bias = self._relative_position_to_absolute_position(relative_logits)
|
| 1094 |
attn_weights += rel_pos_bias
|
| 1095 |
|
| 1096 |
if attention_mask is not None:
|
| 1097 |
-
|
| 1098 |
-
raise ValueError(
|
| 1099 |
-
f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
|
| 1100 |
-
)
|
| 1101 |
attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
|
| 1102 |
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
|
| 1103 |
-
|
| 1104 |
-
# Is possible that starting frames of this attentio hold the choice of voice to place the generation in male or female for german
|
| 1105 |
-
# 1. Is plausible to have some pre-append or post-append frames (whose TTS is always male or female )
|
| 1106 |
-
|
| 1107 |
-
#
|
| 1108 |
-
# --
|
| 1109 |
-
# ___IN attn 1110__ torch.Size([2, 927, 927])
|
| 1110 |
-
# ___IN attn 1110__ torch.Size([2, 927, 927])
|
| 1111 |
-
# ___IN attn 1110__ torch.Size([2, 927, 927])
|
| 1112 |
-
# ___IN attn 1110__ torch.Size([2, 927, 927])
|
| 1113 |
-
# ___IN attn 1110__ torch.Size([2, 927, 927])
|
| 1114 |
-
# ___IN attn 1110__ torch.Size([2, 927, 927]) # this appears to use always thefull len of bert hidden states
|
| 1115 |
-
# --
|
| 1116 |
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
|
|
|
|
|
|
|
| 1117 |
|
| 1118 |
-
attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
|
| 1119 |
|
| 1120 |
-
attn_output = torch.bmm(attn_probs, value_states)
|
| 1121 |
-
|
| 1122 |
-
if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
|
| 1123 |
-
raise ValueError(
|
| 1124 |
-
f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
|
| 1125 |
-
f" {attn_output.size()}"
|
| 1126 |
-
)
|
| 1127 |
|
| 1128 |
if self.window_size is not None:
|
| 1129 |
# Entering here with self.window_size = 4
|
| 1130 |
value_relative_embeddings = self._get_relative_embeddings(self.emb_rel_v, src_len)
|
| 1131 |
-
relative_weights = self._absolute_position_to_relative_position(
|
| 1132 |
rel_pos_bias = torch.matmul(relative_weights, value_relative_embeddings)
|
| 1133 |
attn_output += rel_pos_bias
|
| 1134 |
|
|
@@ -1185,12 +923,8 @@ class VitsFeedForward(nn.Module):
|
|
| 1185 |
super().__init__()
|
| 1186 |
self.conv_1 = nn.Conv1d(config.hidden_size, config.ffn_dim, config.ffn_kernel_size)
|
| 1187 |
self.conv_2 = nn.Conv1d(config.ffn_dim, config.hidden_size, config.ffn_kernel_size)
|
| 1188 |
-
self.
|
| 1189 |
-
|
| 1190 |
-
if isinstance(config.hidden_act, str):
|
| 1191 |
-
self.act_fn = ACT2FN[config.hidden_act]
|
| 1192 |
-
else:
|
| 1193 |
-
self.act_fn = config.hidden_act
|
| 1194 |
|
| 1195 |
if config.ffn_kernel_size > 1:
|
| 1196 |
pad_left = (config.ffn_kernel_size - 1) // 2
|
|
@@ -1209,7 +943,7 @@ class VitsFeedForward(nn.Module):
|
|
| 1209 |
|
| 1210 |
hidden_states = self.conv_1(hidden_states)
|
| 1211 |
hidden_states = self.act_fn(hidden_states)
|
| 1212 |
-
|
| 1213 |
|
| 1214 |
hidden_states = hidden_states * padding_mask
|
| 1215 |
if self.padding is not None:
|
|
@@ -1223,10 +957,10 @@ class VitsFeedForward(nn.Module):
|
|
| 1223 |
|
| 1224 |
|
| 1225 |
class VitsEncoderLayer(nn.Module):
|
| 1226 |
-
def __init__(self, config
|
| 1227 |
super().__init__()
|
| 1228 |
self.attention = VitsAttention(config)
|
| 1229 |
-
|
| 1230 |
self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 1231 |
self.feed_forward = VitsFeedForward(config)
|
| 1232 |
self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
|
@@ -1245,12 +979,12 @@ class VitsEncoderLayer(nn.Module):
|
|
| 1245 |
output_attentions=output_attentions,
|
| 1246 |
)
|
| 1247 |
|
| 1248 |
-
|
| 1249 |
hidden_states = self.layer_norm(residual + hidden_states)
|
| 1250 |
|
| 1251 |
residual = hidden_states
|
| 1252 |
hidden_states = self.feed_forward(hidden_states, padding_mask)
|
| 1253 |
-
|
| 1254 |
hidden_states = self.final_layer_norm(residual + hidden_states)
|
| 1255 |
|
| 1256 |
outputs = (hidden_states,)
|
|
@@ -1262,7 +996,7 @@ class VitsEncoderLayer(nn.Module):
|
|
| 1262 |
|
| 1263 |
|
| 1264 |
class VitsEncoder(nn.Module):
|
| 1265 |
-
def __init__(self, config
|
| 1266 |
super().__init__()
|
| 1267 |
self.config = config
|
| 1268 |
self.layers = nn.ModuleList([VitsEncoderLayer(config) for _ in range(config.num_hidden_layers)])
|
|
@@ -1277,7 +1011,7 @@ class VitsEncoder(nn.Module):
|
|
| 1277 |
output_attentions: Optional[bool] = None,
|
| 1278 |
output_hidden_states: Optional[bool] = None,
|
| 1279 |
return_dict: Optional[bool] = None,
|
| 1280 |
-
)
|
| 1281 |
all_hidden_states = () if output_hidden_states else None
|
| 1282 |
all_self_attentions = () if output_attentions else None
|
| 1283 |
|
|
@@ -1293,11 +1027,6 @@ class VitsEncoder(nn.Module):
|
|
| 1293 |
for encoder_layer in self.layers:
|
| 1294 |
if output_hidden_states:
|
| 1295 |
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 1296 |
-
|
| 1297 |
-
# add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
|
| 1298 |
-
dropout_probability = np.random.uniform(0, 1)
|
| 1299 |
-
|
| 1300 |
-
skip_the_layer = self.training and (dropout_probability < self.layerdrop)
|
| 1301 |
|
| 1302 |
layer_outputs = encoder_layer(
|
| 1303 |
hidden_states,
|
|
@@ -1306,21 +1035,12 @@ class VitsEncoder(nn.Module):
|
|
| 1306 |
output_attentions=output_attentions,
|
| 1307 |
)
|
| 1308 |
hidden_states = layer_outputs[0]
|
| 1309 |
-
|
| 1310 |
-
if skip_the_layer:
|
| 1311 |
-
layer_outputs = (None, None)
|
| 1312 |
-
|
| 1313 |
if output_attentions:
|
| 1314 |
all_self_attentions = all_self_attentions + (layer_outputs[1],)
|
| 1315 |
|
| 1316 |
hidden_states = hidden_states * padding_mask
|
| 1317 |
|
| 1318 |
-
if output_hidden_states:
|
| 1319 |
-
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 1320 |
-
|
| 1321 |
-
if not return_dict:
|
| 1322 |
-
return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
|
| 1323 |
-
|
| 1324 |
return BaseModelOutput(
|
| 1325 |
last_hidden_state=hidden_states,
|
| 1326 |
hidden_states=all_hidden_states,
|
|
@@ -1333,18 +1053,18 @@ class VitsTextEncoder(nn.Module):
|
|
| 1333 |
Transformer encoder that uses relative positional representation instead of absolute positional encoding.
|
| 1334 |
"""
|
| 1335 |
|
| 1336 |
-
def __init__(self, config
|
| 1337 |
super().__init__()
|
| 1338 |
self.config = config
|
| 1339 |
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, config.pad_token_id)
|
| 1340 |
self.encoder = VitsEncoder(config) # 6 Layers of VitsAttention
|
| 1341 |
self.project = nn.Conv1d(config.hidden_size, config.flow_size * 2, kernel_size=1)
|
| 1342 |
|
| 1343 |
-
def get_input_embeddings(self):
|
| 1344 |
-
|
| 1345 |
|
| 1346 |
-
def set_input_embeddings(self, value):
|
| 1347 |
-
|
| 1348 |
|
| 1349 |
def forward(
|
| 1350 |
self,
|
|
@@ -1354,7 +1074,7 @@ class VitsTextEncoder(nn.Module):
|
|
| 1354 |
output_attentions: Optional[bool] = None,
|
| 1355 |
output_hidden_states: Optional[bool] = None,
|
| 1356 |
return_dict: Optional[bool] = True,
|
| 1357 |
-
)
|
| 1358 |
hidden_states = self.embed_tokens(input_ids) * math.sqrt(self.config.hidden_size)
|
| 1359 |
|
| 1360 |
encoder_outputs = self.encoder(
|
|
@@ -1371,10 +1091,6 @@ class VitsTextEncoder(nn.Module):
|
|
| 1371 |
stats = self.project(last_hidden_state.transpose(1, 2)).transpose(1, 2) * padding_mask
|
| 1372 |
prior_means, prior_log_variances = torch.split(stats, self.config.flow_size, dim=2)
|
| 1373 |
|
| 1374 |
-
if not return_dict:
|
| 1375 |
-
outputs = (last_hidden_state, prior_means, prior_log_variances) + encoder_outputs[1:]
|
| 1376 |
-
return outputs
|
| 1377 |
-
|
| 1378 |
return VitsTextEncoderOutput(
|
| 1379 |
last_hidden_state=last_hidden_state,
|
| 1380 |
prior_means=prior_means,
|
|
@@ -1416,7 +1132,7 @@ class VitsPreTrainedModel(PreTrainedModel):
|
|
| 1416 |
|
| 1417 |
|
| 1418 |
class VitsModel(VitsPreTrainedModel):
|
| 1419 |
-
def __init__(self, config
|
| 1420 |
super().__init__(config)
|
| 1421 |
self.config = config
|
| 1422 |
self.text_encoder = VitsTextEncoder(config) # has VitsEncoder that includes 6L of VitsAttention
|
|
@@ -1426,13 +1142,14 @@ class VitsModel(VitsPreTrainedModel):
|
|
| 1426 |
if config.use_stochastic_duration_prediction:
|
| 1427 |
self.duration_predictor = VitsStochasticDurationPredictor(config)
|
| 1428 |
else:
|
| 1429 |
-
|
|
|
|
| 1430 |
|
| 1431 |
if config.num_speakers > 1:
|
| 1432 |
self.embed_speaker = nn.Embedding(config.num_speakers, config.speaker_embedding_size)
|
| 1433 |
|
| 1434 |
-
|
| 1435 |
-
|
| 1436 |
self.noise_scale = config.noise_scale
|
| 1437 |
self.noise_scale_duration = config.noise_scale_duration
|
| 1438 |
|
|
@@ -1451,33 +1168,9 @@ class VitsModel(VitsPreTrainedModel):
|
|
| 1451 |
output_hidden_states = None,
|
| 1452 |
return_dict = None,
|
| 1453 |
labels = None,
|
|
|
|
| 1454 |
):
|
| 1455 |
-
r"""
|
| 1456 |
-
labels (`torch.FloatTensor` of shape `(batch_size, config.spectrogram_bins, sequence_length)`, *optional*):
|
| 1457 |
-
Float values of target spectrogram. Timesteps set to `-100.0` are ignored (masked) for the loss
|
| 1458 |
-
computation.
|
| 1459 |
-
|
| 1460 |
-
Returns:
|
| 1461 |
-
|
| 1462 |
-
Example:
|
| 1463 |
-
|
| 1464 |
-
```python
|
| 1465 |
-
>>> from transformers import VitsTokenizer, VitsModel, set_seed
|
| 1466 |
-
>>> import torch
|
| 1467 |
-
|
| 1468 |
-
>>> tokenizer = VitsTokenizer.from_pretrained("facebook/mms-tts-eng")
|
| 1469 |
-
>>> model = VitsModel.from_pretrained("facebook/mms-tts-eng")
|
| 1470 |
-
|
| 1471 |
-
>>> inputs = tokenizer(text="Hello - my dog is cute", return_tensors="pt")
|
| 1472 |
-
|
| 1473 |
-
>>> set_seed(555) # make deterministic
|
| 1474 |
|
| 1475 |
-
>>> with torch.no_grad():
|
| 1476 |
-
... outputs = model(inputs["input_ids"])
|
| 1477 |
-
>>> outputs.waveform.shape
|
| 1478 |
-
torch.Size([1, 45824])
|
| 1479 |
-
```
|
| 1480 |
-
"""
|
| 1481 |
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1482 |
output_hidden_states = (
|
| 1483 |
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
|
@@ -1528,7 +1221,7 @@ class VitsModel(VitsPreTrainedModel):
|
|
| 1528 |
raise ValueError
|
| 1529 |
# log_duration = self.duration_predictor(hidden_states, input_padding_mask, speaker_embeddings)
|
| 1530 |
|
| 1531 |
-
length_scale = 1.0 /
|
| 1532 |
duration = torch.ceil(torch.exp(log_duration) * input_padding_mask * length_scale)
|
| 1533 |
predicted_lengths = torch.clamp_min(torch.sum(duration, [1, 2]), 1).long()
|
| 1534 |
|
|
|
|
| 5 |
import torch
|
| 6 |
import torch.utils.checkpoint
|
| 7 |
from torch import nn
|
| 8 |
+
|
| 9 |
from transformers.modeling_attn_mask_utils import _prepare_4d_attention_mask
|
| 10 |
from transformers.modeling_outputs import BaseModelOutput, ModelOutput
|
| 11 |
from transformers.modeling_utils import PreTrainedModel
|
| 12 |
from transformers.configuration_utils import PretrainedConfig
|
| 13 |
|
| 14 |
class VitsConfig(PretrainedConfig):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
model_type = "vits"
|
| 17 |
|
|
|
|
| 28 |
ffn_kernel_size=3,
|
| 29 |
flow_size=192,
|
| 30 |
spectrogram_bins=513,
|
| 31 |
+
# hidden_act="relu",
|
| 32 |
hidden_dropout=0.1,
|
| 33 |
attention_dropout=0.1,
|
| 34 |
activation_dropout=0.1,
|
|
|
|
| 57 |
wavenet_kernel_size=5,
|
| 58 |
wavenet_dilation_rate=1,
|
| 59 |
wavenet_dropout=0.0,
|
| 60 |
+
speaking_rate=1.0, # unused
|
| 61 |
noise_scale=0.667,
|
| 62 |
noise_scale_duration=0.8,
|
| 63 |
sampling_rate=16_000,
|
|
|
|
| 74 |
self.ffn_kernel_size = ffn_kernel_size
|
| 75 |
self.flow_size = flow_size
|
| 76 |
self.spectrogram_bins = spectrogram_bins
|
| 77 |
+
|
| 78 |
+
|
|
|
|
|
|
|
| 79 |
self.initializer_range = initializer_range
|
| 80 |
self.layer_norm_eps = layer_norm_eps
|
| 81 |
self.use_stochastic_duration_prediction = use_stochastic_duration_prediction
|
|
|
|
| 92 |
self.duration_predictor_flow_bins = duration_predictor_flow_bins
|
| 93 |
self.duration_predictor_tail_bound = duration_predictor_tail_bound
|
| 94 |
self.duration_predictor_kernel_size = duration_predictor_kernel_size
|
| 95 |
+
|
| 96 |
self.duration_predictor_num_flows = duration_predictor_num_flows
|
| 97 |
self.duration_predictor_filter_channels = duration_predictor_filter_channels
|
| 98 |
self.prior_encoder_num_flows = prior_encoder_num_flows
|
|
|
|
| 100 |
self.posterior_encoder_num_wavenet_layers = posterior_encoder_num_wavenet_layers
|
| 101 |
self.wavenet_kernel_size = wavenet_kernel_size
|
| 102 |
self.wavenet_dilation_rate = wavenet_dilation_rate
|
| 103 |
+
|
| 104 |
+
|
| 105 |
self.noise_scale = noise_scale
|
| 106 |
self.noise_scale_duration = noise_scale_duration
|
| 107 |
self.sampling_rate = sampling_rate
|
|
|
|
| 116 |
|
| 117 |
|
| 118 |
|
|
|
|
|
|
|
|
|
|
| 119 |
@dataclass
|
| 120 |
class VitsTextEncoderOutput(ModelOutput):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
last_hidden_state: torch.FloatTensor = None
|
| 122 |
prior_means: torch.FloatTensor = None
|
| 123 |
prior_log_variances: torch.FloatTensor = None
|
| 124 |
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
| 125 |
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
| 126 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
def _unconstrained_rational_quadratic_spline(
|
| 128 |
inputs,
|
| 129 |
unnormalized_widths,
|
|
|
|
| 135 |
min_bin_height=1e-3,
|
| 136 |
min_derivative=1e-3,
|
| 137 |
):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
inside_interval_mask = (inputs >= -tail_bound) & (inputs <= tail_bound)
|
| 139 |
outside_interval_mask = ~inside_interval_mask
|
| 140 |
|
| 141 |
outputs = torch.zeros_like(inputs)
|
| 142 |
+
|
| 143 |
constant = np.log(np.exp(1 - min_derivative) - 1)
|
| 144 |
|
| 145 |
unnormalized_derivatives = nn.functional.pad(unnormalized_derivatives, pad=(1, 1))
|
|
|
|
| 147 |
unnormalized_derivatives[..., -1] = constant
|
| 148 |
|
| 149 |
outputs[outside_interval_mask] = inputs[outside_interval_mask]
|
| 150 |
+
|
| 151 |
|
| 152 |
+
outputs[inside_interval_mask] = _rational_quadratic_spline(
|
| 153 |
inputs=inputs[inside_interval_mask],
|
| 154 |
unnormalized_widths=unnormalized_widths[inside_interval_mask, :],
|
| 155 |
unnormalized_heights=unnormalized_heights[inside_interval_mask, :],
|
|
|
|
| 160 |
min_bin_height=min_bin_height,
|
| 161 |
min_derivative=min_derivative,
|
| 162 |
)
|
| 163 |
+
return outputs
|
| 164 |
|
| 165 |
|
| 166 |
def _rational_quadratic_spline(
|
|
|
|
| 259 |
|
| 260 |
intermediate1 = input_derivatives + input_derivatives_plus_one - 2 * input_delta
|
| 261 |
if not reverse:
|
| 262 |
+
raise ValueError
|
| 263 |
+
# theta = (inputs - input_cumwidths) / input_bin_widths
|
| 264 |
+
# theta_one_minus_theta = theta * (1 - theta)
|
| 265 |
+
|
| 266 |
+
# numerator = input_heights * (input_delta * theta.pow(2) + input_derivatives * theta_one_minus_theta)
|
| 267 |
+
# denominator = input_delta + intermediate1 * theta_one_minus_theta
|
| 268 |
+
# outputs = input_cumheights + numerator / denominator
|
| 269 |
+
|
| 270 |
+
# derivative_numerator = input_delta.pow(2) * (
|
| 271 |
+
# input_derivatives_plus_one * theta.pow(2)
|
| 272 |
+
# + 2 * input_delta * theta_one_minus_theta
|
| 273 |
+
# + input_derivatives * (1 - theta).pow(2)
|
| 274 |
+
# )
|
| 275 |
+
# log_abs_det = torch.log(derivative_numerator) - 2 * torch.log(denominator)
|
| 276 |
+
# return outputs, log_abs_det
|
| 277 |
else:
|
| 278 |
# find the roots of a quadratic equation
|
| 279 |
intermediate2 = inputs - input_cumheights
|
|
|
|
| 289 |
root = (2 * c) / (-b - torch.sqrt(discriminant))
|
| 290 |
outputs = root * input_bin_widths + input_cumwidths
|
| 291 |
|
| 292 |
+
# theta_one_minus_theta = root * (1 - root)
|
| 293 |
+
# denominator = input_delta + intermediate1 * theta_one_minus_theta
|
| 294 |
+
# derivative_numerator = input_delta.pow(2) * (
|
| 295 |
+
# input_derivatives_plus_one * root.pow(2)
|
| 296 |
+
# + 2 * input_delta * theta_one_minus_theta
|
| 297 |
+
# + input_derivatives * (1 - root).pow(2)
|
| 298 |
+
# )
|
| 299 |
+
# log_abs_det = torch.log(derivative_numerator) - 2 * torch.log(denominator)
|
| 300 |
+
return outputs #, -log_abs_det
|
| 301 |
|
| 302 |
|
| 303 |
class VitsWaveNet(torch.nn.Module):
|
| 304 |
+
def __init__(self, config, num_layers):
|
| 305 |
super().__init__()
|
| 306 |
self.hidden_size = config.hidden_size
|
| 307 |
self.num_layers = num_layers
|
| 308 |
|
| 309 |
self.in_layers = torch.nn.ModuleList()
|
| 310 |
self.res_skip_layers = torch.nn.ModuleList()
|
| 311 |
+
|
| 312 |
|
| 313 |
if hasattr(nn.utils.parametrizations, "weight_norm"):
|
| 314 |
weight_norm = nn.utils.parametrizations.weight_norm
|
|
|
|
| 344 |
|
| 345 |
def forward(self, inputs, padding_mask, global_conditioning=None):
|
| 346 |
outputs = torch.zeros_like(inputs)
|
| 347 |
+
num_channels = torch.IntTensor([self.hidden_size])[0]
|
| 348 |
|
|
|
|
|
|
|
| 349 |
|
| 350 |
for i in range(self.num_layers):
|
| 351 |
+
in_act = self.in_layers[i](inputs)
|
| 352 |
|
| 353 |
+
|
| 354 |
+
# global_states = torch.zeros_like(hidden_states) # style ?
|
|
|
|
|
|
|
|
|
|
| 355 |
|
| 356 |
+
# acts = fused_add_tanh_sigmoid_multiply(hidden_states, global_states, num_channels_tensor[0])
|
| 357 |
+
|
| 358 |
+
# --
|
| 359 |
+
# def fused_add_tanh_sigmoid_multiply(input_a, input_b, num_channels):
|
| 360 |
+
# in_act = input_a # + input_b
|
| 361 |
+
t_act = torch.tanh(in_act[:, :num_channels, :])
|
| 362 |
+
s_act = torch.sigmoid(in_act[:, num_channels:, :])
|
| 363 |
+
acts = t_act * s_act
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
#
|
| 367 |
+
|
| 368 |
+
|
| 369 |
|
| 370 |
res_skip_acts = self.res_skip_layers[i](acts)
|
| 371 |
if i < self.num_layers - 1:
|
|
|
|
| 453 |
|
| 454 |
|
| 455 |
class VitsHifiGan(nn.Module):
|
| 456 |
+
def __init__(self, config):
|
| 457 |
super().__init__()
|
| 458 |
self.config = config
|
| 459 |
self.num_kernels = len(config.resblock_kernel_sizes)
|
|
|
|
| 506 |
layer.remove_weight_norm()
|
| 507 |
|
| 508 |
def forward(
|
| 509 |
+
self,
|
| 510 |
+
spectrogram,
|
| 511 |
+
global_conditioning=None):
|
| 512 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 513 |
hidden_states = self.conv_pre(spectrogram)
|
| 514 |
|
|
|
|
|
|
|
|
|
|
| 515 |
for i in range(self.num_upsamples):
|
| 516 |
hidden_states = nn.functional.leaky_relu(hidden_states, self.config.leaky_relu_slope)
|
| 517 |
hidden_states = self.upsampler[i](hidden_states)
|
|
|
|
| 528 |
|
| 529 |
|
| 530 |
class VitsResidualCouplingLayer(nn.Module):
|
| 531 |
+
def __init__(self, config):
|
| 532 |
super().__init__()
|
| 533 |
self.half_channels = config.flow_size // 2
|
| 534 |
|
|
|
|
| 555 |
|
| 556 |
|
| 557 |
class VitsResidualCouplingBlock(nn.Module):
|
| 558 |
+
def __init__(self, config):
|
| 559 |
super().__init__()
|
| 560 |
self.flows = nn.ModuleList()
|
| 561 |
for _ in range(config.prior_encoder_num_flows):
|
|
|
|
| 574 |
|
| 575 |
|
| 576 |
class VitsDilatedDepthSeparableConv(nn.Module):
|
| 577 |
+
def __init__(self, config, dropout_rate=0.0):
|
| 578 |
super().__init__()
|
| 579 |
kernel_size = config.duration_predictor_kernel_size
|
| 580 |
channels = config.hidden_size
|
| 581 |
self.num_layers = config.depth_separable_num_layers
|
| 582 |
|
|
|
|
| 583 |
self.convs_dilated = nn.ModuleList()
|
| 584 |
self.convs_pointwise = nn.ModuleList()
|
| 585 |
self.norms_1 = nn.ModuleList()
|
|
|
|
| 612 |
hidden_states = self.convs_pointwise[i](hidden_states)
|
| 613 |
hidden_states = self.norms_2[i](hidden_states.transpose(1, -1)).transpose(1, -1)
|
| 614 |
hidden_states = nn.functional.gelu(hidden_states)
|
| 615 |
+
|
| 616 |
inputs = inputs + hidden_states
|
| 617 |
|
| 618 |
return inputs * padding_mask
|
| 619 |
|
| 620 |
|
| 621 |
class VitsConvFlow(nn.Module):
|
| 622 |
+
def __init__(self, config):
|
| 623 |
super().__init__()
|
| 624 |
self.filter_channels = config.hidden_size
|
| 625 |
self.half_channels = config.depth_separable_channels // 2
|
|
|
|
| 644 |
unnormalized_heights = hidden_states[..., self.num_bins : 2 * self.num_bins] / math.sqrt(self.filter_channels)
|
| 645 |
unnormalized_derivatives = hidden_states[..., 2 * self.num_bins :]
|
| 646 |
|
| 647 |
+
second_half = _unconstrained_rational_quadratic_spline(
|
| 648 |
second_half,
|
| 649 |
unnormalized_widths,
|
| 650 |
unnormalized_heights,
|
|
|
|
| 654 |
)
|
| 655 |
|
| 656 |
outputs = torch.cat([first_half, second_half], dim=1) * padding_mask
|
| 657 |
+
|
| 658 |
+
return outputs, None
|
|
|
|
|
|
|
|
|
|
| 659 |
|
| 660 |
|
| 661 |
class VitsElementwiseAffine(nn.Module):
|
|
|
|
| 667 |
|
| 668 |
def forward(self, inputs, padding_mask, global_conditioning=None, reverse=False):
|
| 669 |
if not reverse:
|
| 670 |
+
raise ValueError
|
| 671 |
+
# outputs = self.translate + torch.exp(self.log_scale) * inputs
|
| 672 |
+
# outputs = outputs * padding_mask
|
| 673 |
+
# log_determinant = torch.sum(self.log_scale * padding_mask, [1, 2])
|
| 674 |
+
# return outputs, log_determinant
|
| 675 |
else:
|
| 676 |
outputs = (inputs - self.translate) * torch.exp(-self.log_scale) * padding_mask
|
| 677 |
return outputs, None
|
|
|
|
| 685 |
|
| 686 |
self.conv_pre = nn.Conv1d(filter_channels, filter_channels, 1)
|
| 687 |
self.conv_proj = nn.Conv1d(filter_channels, filter_channels, 1)
|
| 688 |
+
self.conv_dds = VitsDilatedDepthSeparableConv(config)
|
|
|
|
|
|
|
|
|
|
| 689 |
|
| 690 |
if embed_dim != 0:
|
| 691 |
self.cond = nn.Conv1d(embed_dim, filter_channels, 1)
|
|
|
|
| 695 |
for _ in range(config.duration_predictor_num_flows):
|
| 696 |
self.flows.append(VitsConvFlow(config))
|
| 697 |
|
| 698 |
+
# self.post_conv_pre = nn.Conv1d(1, filter_channels, 1)
|
| 699 |
+
# self.post_conv_proj = nn.Conv1d(filter_channels, filter_channels, 1)
|
| 700 |
+
# self.post_conv_dds = VitsDilatedDepthSeparableConv(
|
| 701 |
+
# config,
|
| 702 |
+
# dropout_rate=config.duration_predictor_dropout,
|
| 703 |
+
# )
|
| 704 |
|
| 705 |
+
# self.post_flows = nn.ModuleList()
|
| 706 |
+
# self.post_flows.append(VitsElementwiseAffine(config))
|
| 707 |
+
# for _ in range(config.duration_predictor_num_flows):
|
| 708 |
+
# self.post_flows.append(VitsConvFlow(config))
|
| 709 |
|
| 710 |
def forward(self, inputs, padding_mask, global_conditioning=None, durations=None, reverse=False, noise_scale=1.0):
|
| 711 |
inputs = torch.detach(inputs)
|
| 712 |
inputs = self.conv_pre(inputs)
|
| 713 |
|
| 714 |
if global_conditioning is not None:
|
| 715 |
+
raise ValueError
|
| 716 |
+
# global_conditioning = torch.detach(global_conditioning)
|
| 717 |
+
# inputs = inputs + self.cond(global_conditioning)
|
| 718 |
|
| 719 |
inputs = self.conv_dds(inputs, padding_mask)
|
| 720 |
inputs = self.conv_proj(inputs) * padding_mask
|
| 721 |
|
| 722 |
if not reverse:
|
| 723 |
+
raise ValueError
|
| 724 |
+
# hidden_states = self.post_conv_pre(durations)
|
| 725 |
+
# hidden_states = self.post_conv_dds(hidden_states, padding_mask)
|
| 726 |
+
# hidden_states = self.post_conv_proj(hidden_states) * padding_mask
|
| 727 |
+
|
| 728 |
+
# random_posterior = (
|
| 729 |
+
# torch.randn(durations.size(0), 2, durations.size(2)).to(device=inputs.device, dtype=inputs.dtype)
|
| 730 |
+
# * padding_mask
|
| 731 |
+
# )
|
| 732 |
+
# log_determinant_posterior_sum = 0
|
| 733 |
+
# latents_posterior = random_posterior
|
| 734 |
+
# for flow in self.post_flows:
|
| 735 |
+
# latents_posterior, log_determinant = flow(
|
| 736 |
+
# latents_posterior, padding_mask, global_conditioning=inputs + hidden_states
|
| 737 |
+
# )
|
| 738 |
+
# latents_posterior = torch.flip(latents_posterior, [1])
|
| 739 |
+
# log_determinant_posterior_sum += log_determinant
|
| 740 |
+
|
| 741 |
+
# first_half, second_half = torch.split(latents_posterior, [1, 1], dim=1)
|
| 742 |
+
|
| 743 |
+
# log_determinant_posterior_sum += torch.sum(
|
| 744 |
+
# (nn.functional.logsigmoid(first_half) + nn.functional.logsigmoid(-first_half)) * padding_mask, [1, 2]
|
| 745 |
+
# )
|
| 746 |
+
# logq = (
|
| 747 |
+
# torch.sum(-0.5 * (math.log(2 * math.pi) + (random_posterior**2)) * padding_mask, [1, 2])
|
| 748 |
+
# - log_determinant_posterior_sum
|
| 749 |
+
# )
|
| 750 |
+
|
| 751 |
+
# first_half = (durations - torch.sigmoid(first_half)) * padding_mask
|
| 752 |
+
# first_half = torch.log(torch.clamp_min(first_half, 1e-5)) * padding_mask
|
| 753 |
+
# log_determinant_sum = torch.sum(-first_half, [1, 2])
|
| 754 |
+
|
| 755 |
+
# latents = torch.cat([first_half, second_half], dim=1)
|
| 756 |
+
# for flow in self.flows:
|
| 757 |
+
# latents, log_determinant = flow(latents, padding_mask, global_conditioning=inputs)
|
| 758 |
+
# latents = torch.flip(latents, [1])
|
| 759 |
+
# log_determinant_sum += log_determinant
|
| 760 |
+
|
| 761 |
+
# nll = torch.sum(0.5 * (math.log(2 * math.pi) + (latents**2)) * padding_mask, [1, 2]) - log_determinant_sum
|
| 762 |
+
# return nll + logq
|
| 763 |
else:
|
| 764 |
flows = list(reversed(self.flows))
|
| 765 |
flows = flows[:-2] + [flows[-1]] # remove a useless vflow
|
|
|
|
| 776 |
return log_duration
|
| 777 |
|
| 778 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 779 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 780 |
|
| 781 |
|
| 782 |
class VitsAttention(nn.Module):
|
| 783 |
"""Multi-headed attention with relative positional representation."""
|
| 784 |
|
| 785 |
+
def __init__(self, config):
|
| 786 |
super().__init__()
|
| 787 |
self.embed_dim = config.hidden_size
|
| 788 |
self.num_heads = config.num_attention_heads
|
| 789 |
+
|
| 790 |
self.window_size = config.window_size
|
| 791 |
|
| 792 |
self.head_dim = self.embed_dim // self.num_heads
|
|
|
|
| 804 |
self.out_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.use_bias)
|
| 805 |
|
| 806 |
if self.window_size:
|
| 807 |
+
# Those provide relative pos embs for k/v interpolated from 2*4+1 to 1027 time frames - duration of txt
|
| 808 |
self.emb_rel_k = nn.Parameter(torch.randn(1, self.window_size * 2 + 1, self.head_dim) * self.scaling)
|
| 809 |
self.emb_rel_v = nn.Parameter(torch.randn(1, self.window_size * 2 + 1, self.head_dim) * self.scaling)
|
| 810 |
|
| 811 |
+
def _shape(self, tensor, seq_len, bsz):
|
| 812 |
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
| 813 |
|
| 814 |
def forward(
|
|
|
|
| 841 |
src_len = key_states.size(1)
|
| 842 |
attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
|
| 843 |
|
| 844 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
| 845 |
|
| 846 |
if self.window_size is not None:
|
| 847 |
# 4
|
| 848 |
+
# key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, src_len)
|
| 849 |
+
key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, src_len) # try fix k.shape[2] to have consistent voice deu
|
| 850 |
+
# print(f'{self.emb_rel_k.shape=} {key_relative_embeddings.shape=}\n\nL855')
|
| 851 |
relative_logits = torch.matmul(query_states, key_relative_embeddings.transpose(-2, -1))
|
| 852 |
+
# -- only here (key)
|
| 853 |
rel_pos_bias = self._relative_position_to_absolute_position(relative_logits)
|
| 854 |
attn_weights += rel_pos_bias
|
| 855 |
|
| 856 |
if attention_mask is not None:
|
| 857 |
+
|
|
|
|
|
|
|
|
|
|
| 858 |
attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
|
| 859 |
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 860 |
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
|
| 861 |
+
attn_output = torch.bmm(attn_weights,
|
| 862 |
+
value_states)
|
| 863 |
|
|
|
|
| 864 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 865 |
|
| 866 |
if self.window_size is not None:
|
| 867 |
# Entering here with self.window_size = 4
|
| 868 |
value_relative_embeddings = self._get_relative_embeddings(self.emb_rel_v, src_len)
|
| 869 |
+
relative_weights = self._absolute_position_to_relative_position(attn_weights)
|
| 870 |
rel_pos_bias = torch.matmul(relative_weights, value_relative_embeddings)
|
| 871 |
attn_output += rel_pos_bias
|
| 872 |
|
|
|
|
| 923 |
super().__init__()
|
| 924 |
self.conv_1 = nn.Conv1d(config.hidden_size, config.ffn_dim, config.ffn_kernel_size)
|
| 925 |
self.conv_2 = nn.Conv1d(config.ffn_dim, config.hidden_size, config.ffn_kernel_size)
|
| 926 |
+
self.act_fn = nn.ReLU()
|
| 927 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
| 928 |
|
| 929 |
if config.ffn_kernel_size > 1:
|
| 930 |
pad_left = (config.ffn_kernel_size - 1) // 2
|
|
|
|
| 943 |
|
| 944 |
hidden_states = self.conv_1(hidden_states)
|
| 945 |
hidden_states = self.act_fn(hidden_states)
|
| 946 |
+
|
| 947 |
|
| 948 |
hidden_states = hidden_states * padding_mask
|
| 949 |
if self.padding is not None:
|
|
|
|
| 957 |
|
| 958 |
|
| 959 |
class VitsEncoderLayer(nn.Module):
|
| 960 |
+
def __init__(self, config):
|
| 961 |
super().__init__()
|
| 962 |
self.attention = VitsAttention(config)
|
| 963 |
+
|
| 964 |
self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 965 |
self.feed_forward = VitsFeedForward(config)
|
| 966 |
self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
|
|
|
| 979 |
output_attentions=output_attentions,
|
| 980 |
)
|
| 981 |
|
| 982 |
+
|
| 983 |
hidden_states = self.layer_norm(residual + hidden_states)
|
| 984 |
|
| 985 |
residual = hidden_states
|
| 986 |
hidden_states = self.feed_forward(hidden_states, padding_mask)
|
| 987 |
+
|
| 988 |
hidden_states = self.final_layer_norm(residual + hidden_states)
|
| 989 |
|
| 990 |
outputs = (hidden_states,)
|
|
|
|
| 996 |
|
| 997 |
|
| 998 |
class VitsEncoder(nn.Module):
|
| 999 |
+
def __init__(self, config):
|
| 1000 |
super().__init__()
|
| 1001 |
self.config = config
|
| 1002 |
self.layers = nn.ModuleList([VitsEncoderLayer(config) for _ in range(config.num_hidden_layers)])
|
|
|
|
| 1011 |
output_attentions: Optional[bool] = None,
|
| 1012 |
output_hidden_states: Optional[bool] = None,
|
| 1013 |
return_dict: Optional[bool] = None,
|
| 1014 |
+
):
|
| 1015 |
all_hidden_states = () if output_hidden_states else None
|
| 1016 |
all_self_attentions = () if output_attentions else None
|
| 1017 |
|
|
|
|
| 1027 |
for encoder_layer in self.layers:
|
| 1028 |
if output_hidden_states:
|
| 1029 |
all_hidden_states = all_hidden_states + (hidden_states,)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1030 |
|
| 1031 |
layer_outputs = encoder_layer(
|
| 1032 |
hidden_states,
|
|
|
|
| 1035 |
output_attentions=output_attentions,
|
| 1036 |
)
|
| 1037 |
hidden_states = layer_outputs[0]
|
| 1038 |
+
|
|
|
|
|
|
|
|
|
|
| 1039 |
if output_attentions:
|
| 1040 |
all_self_attentions = all_self_attentions + (layer_outputs[1],)
|
| 1041 |
|
| 1042 |
hidden_states = hidden_states * padding_mask
|
| 1043 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1044 |
return BaseModelOutput(
|
| 1045 |
last_hidden_state=hidden_states,
|
| 1046 |
hidden_states=all_hidden_states,
|
|
|
|
| 1053 |
Transformer encoder that uses relative positional representation instead of absolute positional encoding.
|
| 1054 |
"""
|
| 1055 |
|
| 1056 |
+
def __init__(self, config):
|
| 1057 |
super().__init__()
|
| 1058 |
self.config = config
|
| 1059 |
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, config.pad_token_id)
|
| 1060 |
self.encoder = VitsEncoder(config) # 6 Layers of VitsAttention
|
| 1061 |
self.project = nn.Conv1d(config.hidden_size, config.flow_size * 2, kernel_size=1)
|
| 1062 |
|
| 1063 |
+
# def get_input_embeddings(self):
|
| 1064 |
+
# return self.embed_tokens
|
| 1065 |
|
| 1066 |
+
# def set_input_embeddings(self, value):
|
| 1067 |
+
# self.embed_tokens = value
|
| 1068 |
|
| 1069 |
def forward(
|
| 1070 |
self,
|
|
|
|
| 1074 |
output_attentions: Optional[bool] = None,
|
| 1075 |
output_hidden_states: Optional[bool] = None,
|
| 1076 |
return_dict: Optional[bool] = True,
|
| 1077 |
+
):
|
| 1078 |
hidden_states = self.embed_tokens(input_ids) * math.sqrt(self.config.hidden_size)
|
| 1079 |
|
| 1080 |
encoder_outputs = self.encoder(
|
|
|
|
| 1091 |
stats = self.project(last_hidden_state.transpose(1, 2)).transpose(1, 2) * padding_mask
|
| 1092 |
prior_means, prior_log_variances = torch.split(stats, self.config.flow_size, dim=2)
|
| 1093 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1094 |
return VitsTextEncoderOutput(
|
| 1095 |
last_hidden_state=last_hidden_state,
|
| 1096 |
prior_means=prior_means,
|
|
|
|
| 1132 |
|
| 1133 |
|
| 1134 |
class VitsModel(VitsPreTrainedModel):
|
| 1135 |
+
def __init__(self, config):
|
| 1136 |
super().__init__(config)
|
| 1137 |
self.config = config
|
| 1138 |
self.text_encoder = VitsTextEncoder(config) # has VitsEncoder that includes 6L of VitsAttention
|
|
|
|
| 1142 |
if config.use_stochastic_duration_prediction:
|
| 1143 |
self.duration_predictor = VitsStochasticDurationPredictor(config)
|
| 1144 |
else:
|
| 1145 |
+
raise ValueError
|
| 1146 |
+
# self.duration_predictor = VitsDurationPredictor(config)
|
| 1147 |
|
| 1148 |
if config.num_speakers > 1:
|
| 1149 |
self.embed_speaker = nn.Embedding(config.num_speakers, config.speaker_embedding_size)
|
| 1150 |
|
| 1151 |
+
|
| 1152 |
+
|
| 1153 |
self.noise_scale = config.noise_scale
|
| 1154 |
self.noise_scale_duration = config.noise_scale_duration
|
| 1155 |
|
|
|
|
| 1168 |
output_hidden_states = None,
|
| 1169 |
return_dict = None,
|
| 1170 |
labels = None,
|
| 1171 |
+
speed=None,
|
| 1172 |
):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1173 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1174 |
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1175 |
output_hidden_states = (
|
| 1176 |
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
|
|
|
| 1221 |
raise ValueError
|
| 1222 |
# log_duration = self.duration_predictor(hidden_states, input_padding_mask, speaker_embeddings)
|
| 1223 |
|
| 1224 |
+
length_scale = 1.0 / speed
|
| 1225 |
duration = torch.ceil(torch.exp(log_duration) * input_padding_mask * length_scale)
|
| 1226 |
predicted_lengths = torch.clamp_min(torch.sum(duration, [1, 2]), 1).long()
|
| 1227 |
|
Utils/text_utils.py
CHANGED
|
@@ -87,7 +87,8 @@ def split_into_sentences(text):
|
|
| 87 |
# -- even 400 phonemes sometimes OOM in cuda:4
|
| 88 |
sentences = [sub_sent+' ' for s in sentences for sub_sent in textwrap.wrap(s, 300, break_long_words=0)]
|
| 89 |
|
| 90 |
-
if sentences and not sentences[-1]:
|
|
|
|
| 91 |
return sentences
|
| 92 |
|
| 93 |
def store_ssml(text=None,
|
|
|
|
| 87 |
# -- even 400 phonemes sometimes OOM in cuda:4
|
| 88 |
sentences = [sub_sent+' ' for s in sentences for sub_sent in textwrap.wrap(s, 300, break_long_words=0)]
|
| 89 |
|
| 90 |
+
# if sentences and not sentences[-1]:
|
| 91 |
+
# sentences = sentences[:-1]
|
| 92 |
return sentences
|
| 93 |
|
| 94 |
def store_ssml(text=None,
|
api.py
CHANGED
|
@@ -16,10 +16,7 @@ from moviepy.video.VideoClip import ImageClip
|
|
| 16 |
from audiocraft.builders import AudioGen
|
| 17 |
|
| 18 |
CACHE_DIR = 'flask_cache/'
|
| 19 |
-
|
| 20 |
-
sound_generator = AudioGen(
|
| 21 |
-
duration=PIECE_OF_SOUND_DURATION
|
| 22 |
-
).to('cuda:0').eval()
|
| 23 |
|
| 24 |
Path(CACHE_DIR).mkdir(parents=True, exist_ok=True)
|
| 25 |
|
|
@@ -58,22 +55,16 @@ def _resize(image, width=None, height=None, inter=cv2.INTER_AREA):
|
|
| 58 |
# return the resized image
|
| 59 |
return resized
|
| 60 |
|
| 61 |
-
def overlay(x,
|
| 62 |
-
# pre-calculate the n_repeat here then apply torchaudio.resample and repeat insd sound_gen forward()
|
| 63 |
if soundscape is not None:
|
| 64 |
-
|
| 65 |
background = sound_generator.generate(soundscape,
|
| 66 |
-
|
| 67 |
-
|
| 68 |
|
| 69 |
# blend TTS
|
| 70 |
|
| 71 |
x = .5 * x + .5 * background[:len(x)]
|
| 72 |
-
|
| 73 |
-
else:
|
| 74 |
-
|
| 75 |
-
print('sound_background = None')
|
| 76 |
-
|
| 77 |
return x
|
| 78 |
|
| 79 |
|
|
|
|
| 16 |
from audiocraft.builders import AudioGen
|
| 17 |
|
| 18 |
CACHE_DIR = 'flask_cache/'
|
| 19 |
+
sound_generator = AudioGen().to('cuda:0').eval() # duration chosen in generate()
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
Path(CACHE_DIR).mkdir(parents=True, exist_ok=True)
|
| 22 |
|
|
|
|
| 55 |
# return the resized image
|
| 56 |
return resized
|
| 57 |
|
| 58 |
+
def overlay(x,soundscape=None):
|
|
|
|
| 59 |
if soundscape is not None:
|
|
|
|
| 60 |
background = sound_generator.generate(soundscape,
|
| 61 |
+
duration=len(x)/24000 + .74, # seconds - TTS @ 24kHz
|
| 62 |
+
).detach().cpu().numpy() # bs, 11400 @.74s
|
| 63 |
|
| 64 |
# blend TTS
|
| 65 |
|
| 66 |
x = .5 * x + .5 * background[:len(x)]
|
| 67 |
+
# TTS & AudioGen at 24kHz
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
return x
|
| 69 |
|
| 70 |
|
audiocraft/builders.py
CHANGED
|
@@ -11,6 +11,8 @@ from .lm import LMModel
|
|
| 11 |
from .seanet import SEANetDecoder
|
| 12 |
from .vq import ResidualVectorQuantizer
|
| 13 |
|
|
|
|
|
|
|
| 14 |
def _shift(x):
|
| 15 |
# [bs, samples] shift circular each batch elem of sound
|
| 16 |
n = x.shape[1]
|
|
@@ -42,29 +44,26 @@ class AudioGen(nn.Module):
|
|
| 42 |
|
| 43 |
# https://huggingface.co/facebook/audiogen-medium
|
| 44 |
|
| 45 |
-
def __init__(self
|
| 46 |
-
duration=2.24, # s
|
| 47 |
-
):
|
| 48 |
|
| 49 |
super().__init__()
|
| 50 |
self.load_compression_model()
|
| 51 |
self.load_lm_model()
|
| 52 |
-
|
| 53 |
# AudioGen = 16KHZ StyleTTS2 = 24 KHz / MMSTTS = 24 KHz
|
| 54 |
self.resample_fn = torchaudio.transforms.Resample(16000, 24000)
|
| 55 |
-
|
| 56 |
-
@property
|
| 57 |
-
def frame_rate(self):
|
| 58 |
-
return self.compression_model.frame_rate
|
| 59 |
|
| 60 |
def generate(self,
|
| 61 |
descriptions,
|
| 62 |
-
|
|
|
|
| 63 |
|
| 64 |
with torch.no_grad():
|
|
|
|
|
|
|
| 65 |
gen_tokens = self.lm.generate(
|
| 66 |
-
descriptions=[descriptions]*
|
| 67 |
-
max_tokens=int(
|
| 68 |
x = self.compression_model.decode(gen_tokens, None) #[bs, 1, 11840]
|
| 69 |
|
| 70 |
x = x[:, 0, :] # last samples have splash sounds DISCARD 25000 last samples
|
|
@@ -75,7 +74,7 @@ class AudioGen(nn.Module):
|
|
| 75 |
|
| 76 |
# batch size = different sounds for same txt
|
| 77 |
|
| 78 |
-
x = x.repeat(1,
|
| 79 |
|
| 80 |
# less periodic - shift every batch elem
|
| 81 |
|
|
|
|
| 11 |
from .seanet import SEANetDecoder
|
| 12 |
from .vq import ResidualVectorQuantizer
|
| 13 |
|
| 14 |
+
N_REPEAT = 7 # num (virtual batch_size) clones of audio sounds
|
| 15 |
+
|
| 16 |
def _shift(x):
|
| 17 |
# [bs, samples] shift circular each batch elem of sound
|
| 18 |
n = x.shape[1]
|
|
|
|
| 44 |
|
| 45 |
# https://huggingface.co/facebook/audiogen-medium
|
| 46 |
|
| 47 |
+
def __init__(self):
|
|
|
|
|
|
|
| 48 |
|
| 49 |
super().__init__()
|
| 50 |
self.load_compression_model()
|
| 51 |
self.load_lm_model()
|
| 52 |
+
|
| 53 |
# AudioGen = 16KHZ StyleTTS2 = 24 KHz / MMSTTS = 24 KHz
|
| 54 |
self.resample_fn = torchaudio.transforms.Resample(16000, 24000)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
def generate(self,
|
| 57 |
descriptions,
|
| 58 |
+
duration=2.24, ## seconds of audio
|
| 59 |
+
):
|
| 60 |
|
| 61 |
with torch.no_grad():
|
| 62 |
+
print(duration / N_REPEAT * self.compression_model.frame_rate, 'DURATION TOKENS AudioGen')
|
| 63 |
+
|
| 64 |
gen_tokens = self.lm.generate(
|
| 65 |
+
descriptions=[descriptions] * N_REPEAT,
|
| 66 |
+
max_tokens=int(duration / N_REPEAT * self.compression_model.frame_rate)) # [bs, 4, 37 * self.lm.n_draw]
|
| 67 |
x = self.compression_model.decode(gen_tokens, None) #[bs, 1, 11840]
|
| 68 |
|
| 69 |
x = x[:, 0, :] # last samples have splash sounds DISCARD 25000 last samples
|
|
|
|
| 74 |
|
| 75 |
# batch size = different sounds for same txt
|
| 76 |
|
| 77 |
+
x = x.repeat(1, N_REPEAT)
|
| 78 |
|
| 79 |
# less periodic - shift every batch elem
|
| 80 |
|
audiocraft/transformer.py
CHANGED
|
@@ -32,15 +32,18 @@ class StreamingMultiheadAttention(nn.Module):
|
|
| 32 |
def __init__(self,
|
| 33 |
embed_dim,
|
| 34 |
num_heads,
|
| 35 |
-
cross_attention = False
|
|
|
|
|
|
|
| 36 |
super().__init__()
|
|
|
|
| 37 |
self.cross_attention = cross_attention
|
| 38 |
self.embed_dim = embed_dim
|
| 39 |
self.k_history = None # previous k from the previous tokens seen in the current generation - only for selt.attn
|
| 40 |
self.v_history = None # clean up IN LM after finishing GENERATION - Each 1...47 mha has different kv history
|
| 41 |
self.num_heads = num_heads
|
| 42 |
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=False)
|
| 43 |
-
self.register_buffer('in_proj_weight', torch.ones((3 * embed_dim, embed_dim),
|
| 44 |
dtype=torch.float))
|
| 45 |
|
| 46 |
def forward(self,
|
|
@@ -62,7 +65,7 @@ class StreamingMultiheadAttention(nn.Module):
|
|
| 62 |
# print(q.shape, k.shape, v.shape, q.sum(), k.sum(), v.sum(),'CROSS A5')
|
| 63 |
else:
|
| 64 |
# 1st projected makes k,v (instantaneous)
|
| 65 |
-
#
|
| 66 |
|
| 67 |
|
| 68 |
# HISTORY - DIFFERENT FOR EACH TRANSF LAYER
|
|
@@ -75,12 +78,21 @@ class StreamingMultiheadAttention(nn.Module):
|
|
| 75 |
|
| 76 |
|
| 77 |
if self.k_history is not None:
|
| 78 |
-
#
|
| 79 |
-
#
|
| 80 |
-
# has to be 4D with batch 1 due to single condition 3=seqlen
|
| 81 |
-
# 24 heads 64 dimofh
|
| 82 |
self.k_history = torch.cat([self.k_history, k], 2) # IF ctrl^c here during live demo it is non-atomic k!=v
|
| 83 |
-
self.v_history = torch.cat([self.v_history, v], 2)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
|
| 85 |
else:
|
| 86 |
# init on 1st token (for all 47 transf layers)
|
|
|
|
| 32 |
def __init__(self,
|
| 33 |
embed_dim,
|
| 34 |
num_heads,
|
| 35 |
+
cross_attention = False,
|
| 36 |
+
):
|
| 37 |
+
|
| 38 |
super().__init__()
|
| 39 |
+
|
| 40 |
self.cross_attention = cross_attention
|
| 41 |
self.embed_dim = embed_dim
|
| 42 |
self.k_history = None # previous k from the previous tokens seen in the current generation - only for selt.attn
|
| 43 |
self.v_history = None # clean up IN LM after finishing GENERATION - Each 1...47 mha has different kv history
|
| 44 |
self.num_heads = num_heads
|
| 45 |
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=False)
|
| 46 |
+
self.register_buffer('in_proj_weight', torch.ones((3 * embed_dim, embed_dim),
|
| 47 |
dtype=torch.float))
|
| 48 |
|
| 49 |
def forward(self,
|
|
|
|
| 65 |
# print(q.shape, k.shape, v.shape, q.sum(), k.sum(), v.sum(),'CROSS A5')
|
| 66 |
else:
|
| 67 |
# 1st projected makes k,v (instantaneous)
|
| 68 |
+
# Here else is self_attention for audio with itself (above is cross attention txt)
|
| 69 |
|
| 70 |
|
| 71 |
# HISTORY - DIFFERENT FOR EACH TRANSF LAYER
|
|
|
|
| 78 |
|
| 79 |
|
| 80 |
if self.k_history is not None:
|
| 81 |
+
# k_history.shape = torch.Size([2*N_REPEAT, 24, 3, 64]) FOR cfg > k.shape=torch.Size([2, 24, 1, 64])
|
| 82 |
+
# 24 heads 64 dim
|
|
|
|
|
|
|
| 83 |
self.k_history = torch.cat([self.k_history, k], 2) # IF ctrl^c here during live demo it is non-atomic k!=v
|
| 84 |
+
self.v_history = torch.cat([self.v_history, v], 2) # thus it will try to continue with incompatible k/v dims!
|
| 85 |
+
# Preserve first 4-10 tokens & flush kv
|
| 86 |
+
if self.k_history.shape[2] > 24:
|
| 87 |
+
|
| 88 |
+
# find LOWEST l2 norm of keys > https://arxiv.org/pdf/2406.11430v4
|
| 89 |
+
|
| 90 |
+
low_norm = (self.k_history * self.k_history).mean(3, keepdims=True).sum(1, keepdims=True) # [bs, 24, T, 64] -> [bs, T]
|
| 91 |
+
_, _ix = torch.topk(low_norm, k=10, dim=2, largest=False) # shows background music due to cfg - looses the txt conditioning if flushed!
|
| 92 |
+
_ix = _ix.repeat(1, 24, 1, 64)
|
| 93 |
+
# print(_ix.shape)
|
| 94 |
+
self.k_history = torch.gather(self.k_history, 2, _ix)
|
| 95 |
+
self.v_history = torch.gather(self.v_history, 2, _ix)
|
| 96 |
|
| 97 |
else:
|
| 98 |
# init on 1st token (for all 47 transf layers)
|
demo.py
CHANGED
|
@@ -64,7 +64,7 @@ def tts_entry(text='»Vom Prof. Friedrich ist noch eine recht schöne große Lan
|
|
| 64 |
else:
|
| 65 |
|
| 66 |
# MMS TTS - list of sentences
|
| 67 |
-
x = msinference.foreign(text=
|
| 68 |
lang=voice, # voice = 'romanian', 'serbian' 'hungarian'
|
| 69 |
speed=speed) # normalisation externally
|
| 70 |
|
|
@@ -74,4 +74,4 @@ def tts_entry(text='»Vom Prof. Friedrich ist noch eine recht schöne große Lan
|
|
| 74 |
print(x.shape, 'TTS OK')
|
| 75 |
return x
|
| 76 |
|
| 77 |
-
soundfile.write(f'
|
|
|
|
| 64 |
else:
|
| 65 |
|
| 66 |
# MMS TTS - list of sentences
|
| 67 |
+
x = msinference.foreign(text=text,
|
| 68 |
lang=voice, # voice = 'romanian', 'serbian' 'hungarian'
|
| 69 |
speed=speed) # normalisation externally
|
| 70 |
|
|
|
|
| 74 |
print(x.shape, 'TTS OK')
|
| 75 |
return x
|
| 76 |
|
| 77 |
+
soundfile.write(f'de00i.wav', tts_entry(), 24000)
|
msinference.py
CHANGED
|
@@ -9,7 +9,7 @@ import torchaudio
|
|
| 9 |
import librosa
|
| 10 |
from models import ProsodyPredictor, TextEncoder, StyleEncoder, load_F0_models
|
| 11 |
from nltk.tokenize import word_tokenize
|
| 12 |
-
|
| 13 |
# IPA Phonemizer: https://github.com/bootphon/phonemizer
|
| 14 |
|
| 15 |
_pad = "$"
|
|
@@ -76,10 +76,6 @@ def compute_style(path):
|
|
| 76 |
device = 'cpu'
|
| 77 |
if torch.cuda.is_available():
|
| 78 |
device = 'cuda'
|
| 79 |
-
elif torch.backends.mps.is_available():
|
| 80 |
-
# print("MPS would be available but cannot be used rn")
|
| 81 |
-
pass
|
| 82 |
-
# device = 'mps'
|
| 83 |
|
| 84 |
import phonemizer
|
| 85 |
global_phonemizer = phonemizer.backend.EspeakBackend(language='en-us', preserve_punctuation=True, with_stress=True)
|
|
@@ -311,7 +307,8 @@ def has_cyrillic(text):
|
|
| 311 |
# https://stackoverflow.com/questions/48255244/python-check-if-a-string-contains-cyrillic-characters
|
| 312 |
return bool(re.search('[\u0400-\u04FF]', text))
|
| 313 |
|
| 314 |
-
def foreign(text=None, #
|
|
|
|
| 315 |
lang='romanian',
|
| 316 |
speed=None):
|
| 317 |
|
|
@@ -325,7 +322,7 @@ def foreign(text=None, # list of text
|
|
| 325 |
|
| 326 |
elif any([i in lang for i in ['ser', 'bosn', 'herzegov', 'montenegr', 'macedon']]):
|
| 327 |
|
| 328 |
-
if has_cyrillic(text
|
| 329 |
|
| 330 |
lang_code = 'rmc-script_cyrillic' # romani carpathian (also has latin / cyrillic Vlax)
|
| 331 |
|
|
@@ -356,10 +353,19 @@ def foreign(text=None, # list of text
|
|
| 356 |
|
| 357 |
net_g = VitsModel.from_pretrained(f'facebook/mms-tts-{lang_code}').eval().to(device)
|
| 358 |
tokenizer = VitsTokenizer.from_pretrained(f'facebook/mms-tts-{lang_code}')
|
| 359 |
-
|
| 360 |
# CALL MMS TTS VITS
|
| 361 |
|
| 362 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 363 |
|
| 364 |
for _t in text:
|
| 365 |
|
|
@@ -373,23 +379,27 @@ def foreign(text=None, # list of text
|
|
| 373 |
elif lang_code == 'ron':
|
| 374 |
|
| 375 |
_t = _t.replace("ţ", "ț"
|
| 376 |
-
).replace('ț','ts').replace('î', 'u')
|
| 377 |
|
| 378 |
# /data/dkounadis/.hf7/hub/models--facebook--mms-tts/snapshots/44cc7fb408064ef9ea6e7c59130d88cac1274671/models/rmc-script_latin/vocab.txt
|
| 379 |
inputs = tokenizer(_t, return_tensors="pt") # input_ids / attention_mask
|
| 380 |
-
|
| 381 |
with torch.no_grad():
|
| 382 |
-
# -- reset speed
|
| 383 |
-
net_g.speaking_rate = speed
|
| 384 |
-
# --
|
| 385 |
-
x.append(
|
| 386 |
-
net_g(input_ids=inputs.input_ids.to(device),
|
| 387 |
-
attention_mask=inputs.attention_mask.to(device))
|
| 388 |
-
)
|
| 389 |
-
print(x[-1].shape)
|
| 390 |
-
print(f'{speed=}\n\n\n\n_______________________________ {_t}')
|
| 391 |
|
| 392 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 393 |
|
| 394 |
x /= np.abs(x).max() + 1e-7
|
| 395 |
|
|
|
|
| 9 |
import librosa
|
| 10 |
from models import ProsodyPredictor, TextEncoder, StyleEncoder, load_F0_models
|
| 11 |
from nltk.tokenize import word_tokenize
|
| 12 |
+
import textwrap
|
| 13 |
# IPA Phonemizer: https://github.com/bootphon/phonemizer
|
| 14 |
|
| 15 |
_pad = "$"
|
|
|
|
| 76 |
device = 'cpu'
|
| 77 |
if torch.cuda.is_available():
|
| 78 |
device = 'cuda'
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
|
| 80 |
import phonemizer
|
| 81 |
global_phonemizer = phonemizer.backend.EspeakBackend(language='en-us', preserve_punctuation=True, with_stress=True)
|
|
|
|
| 307 |
# https://stackoverflow.com/questions/48255244/python-check-if-a-string-contains-cyrillic-characters
|
| 308 |
return bool(re.search('[\u0400-\u04FF]', text))
|
| 309 |
|
| 310 |
+
def foreign(text=None, # split sentences here so we can prepend a txt for german to each sentence to
|
| 311 |
+
# fall on the male voice (Sink attn)
|
| 312 |
lang='romanian',
|
| 313 |
speed=None):
|
| 314 |
|
|
|
|
| 322 |
|
| 323 |
elif any([i in lang for i in ['ser', 'bosn', 'herzegov', 'montenegr', 'macedon']]):
|
| 324 |
|
| 325 |
+
if has_cyrillic(text): # check 0-th sentence if is cyrillic
|
| 326 |
|
| 327 |
lang_code = 'rmc-script_cyrillic' # romani carpathian (also has latin / cyrillic Vlax)
|
| 328 |
|
|
|
|
| 353 |
|
| 354 |
net_g = VitsModel.from_pretrained(f'facebook/mms-tts-{lang_code}').eval().to(device)
|
| 355 |
tokenizer = VitsTokenizer.from_pretrained(f'facebook/mms-tts-{lang_code}')
|
| 356 |
+
|
| 357 |
# CALL MMS TTS VITS
|
| 358 |
|
| 359 |
+
total_audio = []
|
| 360 |
+
|
| 361 |
+
# Split long sentences if deu to control voice switch - for other languages let text no-split
|
| 362 |
+
if not isinstance(text, list):
|
| 363 |
+
if lang_code == 'deu':
|
| 364 |
+
# Split Very long sentences >500 phoneme - StyleTTS2 crashes # -- even 400 phonemes sometimes OOM in cuda:4
|
| 365 |
+
# However prosody is nicer on non-split for MMS TTS
|
| 366 |
+
text = [sub_sent+' ' for sub_sent in textwrap.wrap(text, 300, break_long_words=0)]
|
| 367 |
+
else:
|
| 368 |
+
text = [text]
|
| 369 |
|
| 370 |
for _t in text:
|
| 371 |
|
|
|
|
| 379 |
elif lang_code == 'ron':
|
| 380 |
|
| 381 |
_t = _t.replace("ţ", "ț"
|
| 382 |
+
).replace('ț','ts').replace('î', 'u').replace('â','a').replace('ş','s')
|
| 383 |
|
| 384 |
# /data/dkounadis/.hf7/hub/models--facebook--mms-tts/snapshots/44cc7fb408064ef9ea6e7c59130d88cac1274671/models/rmc-script_latin/vocab.txt
|
| 385 |
inputs = tokenizer(_t, return_tensors="pt") # input_ids / attention_mask
|
| 386 |
+
|
| 387 |
with torch.no_grad():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 388 |
|
| 389 |
+
# MMS
|
| 390 |
+
|
| 391 |
+
x = net_g(input_ids=inputs.input_ids.to(device),
|
| 392 |
+
attention_mask=inputs.attention_mask.to(device),
|
| 393 |
+
speed = .94 + .4 * np.random.rand() # variable speed / sentence
|
| 394 |
+
)[0, :]
|
| 395 |
+
|
| 396 |
+
# crop the 1st audio - is PREFIX text 156000 samples to chose deu voice / VitsAttention()
|
| 397 |
+
|
| 398 |
+
total_audio.append(x)
|
| 399 |
+
|
| 400 |
+
print(f'\n\n_______________________________ {_t} {x.shape=}')
|
| 401 |
+
|
| 402 |
+
x = torch.cat(total_audio).cpu().numpy()
|
| 403 |
|
| 404 |
x /= np.abs(x).max() + 1e-7
|
| 405 |
|