anhnct commited on
Commit
7fcc9c8
·
verified ·
1 Parent(s): 62f2843

Upload modeling_vits.py

Browse files
Files changed (1) hide show
  1. modeling_vits.py +1799 -0
modeling_vits.py ADDED
@@ -0,0 +1,1799 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 VITS model."""
16
+
17
+ import math
18
+ from dataclasses import dataclass
19
+ from typing import Any, Optional, Tuple, Union
20
+
21
+ import numpy as np
22
+ import torch
23
+ import torch.utils.checkpoint
24
+ from scipy.signal import get_window, kaiser
25
+ from torch import nn
26
+
27
+ from transformers.activations import ACT2FN
28
+ from transformers.integrations.deepspeed import is_deepspeed_zero3_enabled
29
+ from transformers.integrations.fsdp import is_fsdp_managed_module
30
+ from transformers.modeling_attn_mask_utils import _prepare_4d_attention_mask
31
+ from transformers.modeling_outputs import (
32
+ BaseModelOutput,
33
+ ModelOutput,
34
+ )
35
+ from transformers.modeling_utils import PreTrainedModel
36
+ from transformers.utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
37
+ from .configuration_vits import VitsConfig
38
+
39
+
40
+ logger = logging.get_logger(__name__)
41
+
42
+
43
+ # General docstring
44
+ _CONFIG_FOR_DOC = "VitsConfig"
45
+
46
+
47
+ @dataclass
48
+ class VitsModelOutput(ModelOutput):
49
+ """
50
+ Describes the outputs for the VITS model, with potential hidden states and attentions.
51
+
52
+ Args:
53
+ waveform (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
54
+ The final audio waveform predicted by the model.
55
+ sequence_lengths (`torch.FloatTensor` of shape `(batch_size,)`):
56
+ The length in samples of each element in the `waveform` batch.
57
+ spectrogram (`torch.FloatTensor` of shape `(batch_size, sequence_length, num_bins)`):
58
+ The log-mel spectrogram predicted at the output of the flow model. This spectrogram is passed to the Hi-Fi
59
+ GAN decoder model to obtain the final audio waveform.
60
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
61
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
62
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
63
+
64
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
65
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
66
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
67
+ sequence_length)`.
68
+
69
+ Attention weights after the attention softmax, used to compute the weighted average in the self-attention
70
+ heads.
71
+ """
72
+
73
+ waveform: torch.FloatTensor = None
74
+ sequence_lengths: torch.FloatTensor = None
75
+ spectrogram: Optional[Tuple[torch.FloatTensor]] = None
76
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
77
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
78
+
79
+
80
+ @dataclass
81
+ class VitsTextEncoderOutput(ModelOutput):
82
+ """
83
+ Describes the outputs for the VITS text encoder model, with potential hidden states and attentions.
84
+
85
+ Args:
86
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
87
+ Sequence of hidden-states at the output of the last layer of the model.
88
+ prior_means (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
89
+ The predicted mean values of the prior distribution for the latent text variables.
90
+ prior_log_variances (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
91
+ The predicted log-variance values of the prior distribution for the latent text variables.
92
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
93
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
94
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
95
+
96
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
97
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
98
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
99
+ sequence_length)`.
100
+
101
+ Attention weights after the attention softmax, used to compute the weighted average in the self-attention
102
+ heads.
103
+ """
104
+
105
+ last_hidden_state: torch.FloatTensor = None
106
+ prior_means: torch.FloatTensor = None
107
+ prior_log_variances: torch.FloatTensor = None
108
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
109
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
110
+
111
+
112
+ @torch.jit.script
113
+ def fused_add_tanh_sigmoid_multiply(input_a, input_b, num_channels):
114
+ in_act = input_a + input_b
115
+ t_act = torch.tanh(in_act[:, :num_channels, :])
116
+ s_act = torch.sigmoid(in_act[:, num_channels:, :])
117
+ acts = t_act * s_act
118
+ return acts
119
+
120
+
121
+ def _unconstrained_rational_quadratic_spline(
122
+ inputs,
123
+ unnormalized_widths,
124
+ unnormalized_heights,
125
+ unnormalized_derivatives,
126
+ reverse=False,
127
+ tail_bound=5.0,
128
+ min_bin_width=1e-3,
129
+ min_bin_height=1e-3,
130
+ min_derivative=1e-3,
131
+ ):
132
+ """
133
+ This transformation represents a monotonically increasing piecewise rational quadratic function. Outside of the
134
+ `tail_bound`, the transform behaves as an identity function.
135
+
136
+ Args:
137
+ inputs (`torch.FloatTensor` of shape `(batch_size, channels, seq_len)`:
138
+ Second half of the hidden-states input to the Vits convolutional flow module.
139
+ unnormalized_widths (`torch.FloatTensor` of shape `(batch_size, channels, seq_len, duration_predictor_flow_bins)`):
140
+ First `duration_predictor_flow_bins` of the hidden-states from the output of the convolution projection
141
+ layer in the convolutional flow module
142
+ unnormalized_heights (`torch.FloatTensor` of shape `(batch_size, channels, seq_len, duration_predictor_flow_bins)`):
143
+ Second `duration_predictor_flow_bins` of the hidden-states from the output of the convolution projection
144
+ layer in the convolutional flow module
145
+ unnormalized_derivatives (`torch.FloatTensor` of shape `(batch_size, channels, seq_len, duration_predictor_flow_bins)`):
146
+ Third `duration_predictor_flow_bins` of the hidden-states from the output of the convolution projection
147
+ layer in the convolutional flow module
148
+ reverse (`bool`, *optional*, defaults to `False`):
149
+ Whether the model is being run in reverse mode.
150
+ tail_bound (`float`, *optional* defaults to 5):
151
+ Upper and lower limit bound for the rational quadratic function. Outside of this `tail_bound`, the
152
+ transform behaves as an identity function.
153
+ min_bin_width (`float`, *optional*, defaults to 1e-3):
154
+ Minimum bin value across the width dimension for the piecewise rational quadratic function.
155
+ min_bin_height (`float`, *optional*, defaults to 1e-3):
156
+ Minimum bin value across the height dimension for the piecewise rational quadratic function.
157
+ min_derivative (`float`, *optional*, defaults to 1e-3):
158
+ Minimum bin value across the derivatives for the piecewise rational quadratic function.
159
+ Returns:
160
+ outputs (`torch.FloatTensor` of shape `(batch_size, channels, seq_len)`:
161
+ Hidden-states as transformed by the piecewise rational quadratic function with the `tail_bound` limits
162
+ applied.
163
+ log_abs_det (`torch.FloatTensor` of shape `(batch_size, channels, seq_len)`:
164
+ Logarithm of the absolute value of the determinants corresponding to the `outputs` with the `tail_bound`
165
+ limits applied.
166
+ """
167
+ inside_interval_mask = (inputs >= -tail_bound) & (inputs <= tail_bound)
168
+ outside_interval_mask = ~inside_interval_mask
169
+
170
+ outputs = torch.zeros_like(inputs)
171
+ log_abs_det = torch.zeros_like(inputs)
172
+ constant = np.log(np.exp(1 - min_derivative) - 1)
173
+
174
+ unnormalized_derivatives = nn.functional.pad(unnormalized_derivatives, pad=(1, 1))
175
+ unnormalized_derivatives[..., 0] = constant
176
+ unnormalized_derivatives[..., -1] = constant
177
+
178
+ outputs[outside_interval_mask] = inputs[outside_interval_mask]
179
+ log_abs_det[outside_interval_mask] = 0.0
180
+
181
+ outputs[inside_interval_mask], log_abs_det[inside_interval_mask] = _rational_quadratic_spline(
182
+ inputs=inputs[inside_interval_mask],
183
+ unnormalized_widths=unnormalized_widths[inside_interval_mask, :],
184
+ unnormalized_heights=unnormalized_heights[inside_interval_mask, :],
185
+ unnormalized_derivatives=unnormalized_derivatives[inside_interval_mask, :],
186
+ reverse=reverse,
187
+ tail_bound=tail_bound,
188
+ min_bin_width=min_bin_width,
189
+ min_bin_height=min_bin_height,
190
+ min_derivative=min_derivative,
191
+ )
192
+ return outputs, log_abs_det
193
+
194
+
195
+ def _rational_quadratic_spline(
196
+ inputs,
197
+ unnormalized_widths,
198
+ unnormalized_heights,
199
+ unnormalized_derivatives,
200
+ reverse,
201
+ tail_bound,
202
+ min_bin_width,
203
+ min_bin_height,
204
+ min_derivative,
205
+ ):
206
+ """
207
+ This transformation represents a monotonically increasing piecewise rational quadratic function. Unlike the
208
+ function `_unconstrained_rational_quadratic_spline`, the function behaves the same across the `tail_bound`.
209
+
210
+ Args:
211
+ inputs (`torch.FloatTensor` of shape `(batch_size, channels, seq_len)`:
212
+ Second half of the hidden-states input to the Vits convolutional flow module.
213
+ unnormalized_widths (`torch.FloatTensor` of shape `(batch_size, channels, seq_len, duration_predictor_flow_bins)`):
214
+ First `duration_predictor_flow_bins` of the hidden-states from the output of the convolution projection
215
+ layer in the convolutional flow module
216
+ unnormalized_heights (`torch.FloatTensor` of shape `(batch_size, channels, seq_len, duration_predictor_flow_bins)`):
217
+ Second `duration_predictor_flow_bins` of the hidden-states from the output of the convolution projection
218
+ layer in the convolutional flow module
219
+ unnormalized_derivatives (`torch.FloatTensor` of shape `(batch_size, channels, seq_len, duration_predictor_flow_bins)`):
220
+ Third `duration_predictor_flow_bins` of the hidden-states from the output of the convolution projection
221
+ layer in the convolutional flow module
222
+ reverse (`bool`):
223
+ Whether the model is being run in reverse mode.
224
+ tail_bound (`float`):
225
+ Upper and lower limit bound for the rational quadratic function. Outside of this `tail_bound`, the
226
+ transform behaves as an identity function.
227
+ min_bin_width (`float`):
228
+ Minimum bin value across the width dimension for the piecewise rational quadratic function.
229
+ min_bin_height (`float`):
230
+ Minimum bin value across the height dimension for the piecewise rational quadratic function.
231
+ min_derivative (`float`):
232
+ Minimum bin value across the derivatives for the piecewise rational quadratic function.
233
+ Returns:
234
+ outputs (`torch.FloatTensor` of shape `(batch_size, channels, seq_len)`:
235
+ Hidden-states as transformed by the piecewise rational quadratic function.
236
+ log_abs_det (`torch.FloatTensor` of shape `(batch_size, channels, seq_len)`:
237
+ Logarithm of the absolute value of the determinants corresponding to the `outputs`.
238
+ """
239
+ upper_bound = tail_bound
240
+ lower_bound = -tail_bound
241
+
242
+ if torch.min(inputs) < lower_bound or torch.max(inputs) > upper_bound:
243
+ raise ValueError("Input to a transform is not within its domain")
244
+
245
+ num_bins = unnormalized_widths.shape[-1]
246
+
247
+ if min_bin_width * num_bins > 1.0:
248
+ raise ValueError(f"Minimal bin width {min_bin_width} too large for the number of bins {num_bins}")
249
+ if min_bin_height * num_bins > 1.0:
250
+ raise ValueError(f"Minimal bin height {min_bin_height} too large for the number of bins {num_bins}")
251
+
252
+ widths = nn.functional.softmax(unnormalized_widths, dim=-1)
253
+ widths = min_bin_width + (1 - min_bin_width * num_bins) * widths
254
+ cumwidths = torch.cumsum(widths, dim=-1)
255
+ cumwidths = nn.functional.pad(cumwidths, pad=(1, 0), mode="constant", value=0.0)
256
+ cumwidths = (upper_bound - lower_bound) * cumwidths + lower_bound
257
+ cumwidths[..., 0] = lower_bound
258
+ cumwidths[..., -1] = upper_bound
259
+ widths = cumwidths[..., 1:] - cumwidths[..., :-1]
260
+
261
+ derivatives = min_derivative + nn.functional.softplus(unnormalized_derivatives)
262
+
263
+ heights = nn.functional.softmax(unnormalized_heights, dim=-1)
264
+ heights = min_bin_height + (1 - min_bin_height * num_bins) * heights
265
+ cumheights = torch.cumsum(heights, dim=-1)
266
+ cumheights = nn.functional.pad(cumheights, pad=(1, 0), mode="constant", value=0.0)
267
+ cumheights = (upper_bound - lower_bound) * cumheights + lower_bound
268
+ cumheights[..., 0] = lower_bound
269
+ cumheights[..., -1] = upper_bound
270
+ heights = cumheights[..., 1:] - cumheights[..., :-1]
271
+
272
+ bin_locations = cumheights if reverse else cumwidths
273
+ bin_locations[..., -1] += 1e-6
274
+ bin_idx = torch.sum(inputs[..., None] >= bin_locations, dim=-1) - 1
275
+ bin_idx = bin_idx[..., None]
276
+
277
+ input_cumwidths = cumwidths.gather(-1, bin_idx)[..., 0]
278
+ input_bin_widths = widths.gather(-1, bin_idx)[..., 0]
279
+
280
+ input_cumheights = cumheights.gather(-1, bin_idx)[..., 0]
281
+ delta = heights / widths
282
+ input_delta = delta.gather(-1, bin_idx)[..., 0]
283
+
284
+ input_derivatives = derivatives.gather(-1, bin_idx)[..., 0]
285
+ input_derivatives_plus_one = derivatives[..., 1:].gather(-1, bin_idx)[..., 0]
286
+
287
+ input_heights = heights.gather(-1, bin_idx)[..., 0]
288
+
289
+ intermediate1 = input_derivatives + input_derivatives_plus_one - 2 * input_delta
290
+ if not reverse:
291
+ theta = (inputs - input_cumwidths) / input_bin_widths
292
+ theta_one_minus_theta = theta * (1 - theta)
293
+
294
+ numerator = input_heights * (input_delta * theta.pow(2) + input_derivatives * theta_one_minus_theta)
295
+ denominator = input_delta + intermediate1 * theta_one_minus_theta
296
+ outputs = input_cumheights + numerator / denominator
297
+
298
+ derivative_numerator = input_delta.pow(2) * (
299
+ input_derivatives_plus_one * theta.pow(2)
300
+ + 2 * input_delta * theta_one_minus_theta
301
+ + input_derivatives * (1 - theta).pow(2)
302
+ )
303
+ log_abs_det = torch.log(derivative_numerator) - 2 * torch.log(denominator)
304
+ return outputs, log_abs_det
305
+ else:
306
+ # find the roots of a quadratic equation
307
+ intermediate2 = inputs - input_cumheights
308
+ intermediate3 = intermediate2 * intermediate1
309
+ a = input_heights * (input_delta - input_derivatives) + intermediate3
310
+ b = input_heights * input_derivatives - intermediate3
311
+ c = -input_delta * intermediate2
312
+
313
+ discriminant = b.pow(2) - 4 * a * c
314
+ if not (discriminant >= 0).all():
315
+ raise RuntimeError(f"invalid discriminant {discriminant}")
316
+
317
+ root = (2 * c) / (-b - torch.sqrt(discriminant))
318
+ outputs = root * input_bin_widths + input_cumwidths
319
+
320
+ theta_one_minus_theta = root * (1 - root)
321
+ denominator = input_delta + intermediate1 * theta_one_minus_theta
322
+ derivative_numerator = input_delta.pow(2) * (
323
+ input_derivatives_plus_one * root.pow(2)
324
+ + 2 * input_delta * theta_one_minus_theta
325
+ + input_derivatives * (1 - root).pow(2)
326
+ )
327
+ log_abs_det = torch.log(derivative_numerator) - 2 * torch.log(denominator)
328
+ return outputs, -log_abs_det
329
+
330
+
331
+ class VitsWaveNet(torch.nn.Module):
332
+ def __init__(self, config: VitsConfig, num_layers: int):
333
+ super().__init__()
334
+ self.hidden_size = config.hidden_size
335
+ self.num_layers = num_layers
336
+
337
+ self.in_layers = torch.nn.ModuleList()
338
+ self.res_skip_layers = torch.nn.ModuleList()
339
+ self.dropout = nn.Dropout(config.wavenet_dropout)
340
+
341
+ if hasattr(nn.utils.parametrizations, "weight_norm"):
342
+ weight_norm = nn.utils.parametrizations.weight_norm
343
+ else:
344
+ weight_norm = nn.utils.weight_norm
345
+
346
+ if config.speaker_embedding_size != 0:
347
+ cond_layer = torch.nn.Conv1d(config.speaker_embedding_size, 2 * config.hidden_size * num_layers, 1)
348
+ self.cond_layer = weight_norm(cond_layer, name="weight")
349
+
350
+ for i in range(num_layers):
351
+ dilation = config.wavenet_dilation_rate**i
352
+ padding = (config.wavenet_kernel_size * dilation - dilation) // 2
353
+ in_layer = torch.nn.Conv1d(
354
+ in_channels=config.hidden_size,
355
+ out_channels=2 * config.hidden_size,
356
+ kernel_size=config.wavenet_kernel_size,
357
+ dilation=dilation,
358
+ padding=padding,
359
+ )
360
+ in_layer = weight_norm(in_layer, name="weight")
361
+ self.in_layers.append(in_layer)
362
+
363
+ # last one is not necessary
364
+ if i < num_layers - 1:
365
+ res_skip_channels = 2 * config.hidden_size
366
+ else:
367
+ res_skip_channels = config.hidden_size
368
+
369
+ res_skip_layer = torch.nn.Conv1d(config.hidden_size, res_skip_channels, 1)
370
+ res_skip_layer = weight_norm(res_skip_layer, name="weight")
371
+ self.res_skip_layers.append(res_skip_layer)
372
+
373
+ def forward(self, inputs, padding_mask, global_conditioning=None):
374
+ outputs = torch.zeros_like(inputs)
375
+ num_channels_tensor = torch.IntTensor([self.hidden_size])
376
+
377
+ if global_conditioning is not None:
378
+ global_conditioning = self.cond_layer(global_conditioning)
379
+
380
+ for i in range(self.num_layers):
381
+ hidden_states = self.in_layers[i](inputs)
382
+
383
+ if global_conditioning is not None:
384
+ cond_offset = i * 2 * self.hidden_size
385
+ global_states = global_conditioning[:, cond_offset : cond_offset + 2 * self.hidden_size, :]
386
+ else:
387
+ global_states = torch.zeros_like(hidden_states)
388
+
389
+ acts = fused_add_tanh_sigmoid_multiply(hidden_states, global_states, num_channels_tensor[0])
390
+ acts = self.dropout(acts)
391
+
392
+ res_skip_acts = self.res_skip_layers[i](acts)
393
+ if i < self.num_layers - 1:
394
+ res_acts = res_skip_acts[:, : self.hidden_size, :]
395
+ inputs = (inputs + res_acts) * padding_mask
396
+ outputs = outputs + res_skip_acts[:, self.hidden_size :, :]
397
+ else:
398
+ outputs = outputs + res_skip_acts
399
+
400
+ return outputs * padding_mask
401
+
402
+ def remove_weight_norm(self):
403
+ if self.speaker_embedding_size != 0:
404
+ torch.nn.utils.remove_weight_norm(self.cond_layer)
405
+ for layer in self.in_layers:
406
+ torch.nn.utils.remove_weight_norm(layer)
407
+ for layer in self.res_skip_layers:
408
+ torch.nn.utils.remove_weight_norm(layer)
409
+
410
+
411
+ class VitsPosteriorEncoder(nn.Module):
412
+ def __init__(self, config: VitsConfig):
413
+ super().__init__()
414
+ self.out_channels = config.flow_size
415
+
416
+ self.conv_pre = nn.Conv1d(config.spectrogram_bins, config.hidden_size, 1)
417
+ self.wavenet = VitsWaveNet(config, num_layers=config.posterior_encoder_num_wavenet_layers)
418
+ self.conv_proj = nn.Conv1d(config.hidden_size, self.out_channels * 2, 1)
419
+
420
+ def forward(self, inputs, padding_mask, global_conditioning=None):
421
+ inputs = self.conv_pre(inputs) * padding_mask
422
+ inputs = self.wavenet(inputs, padding_mask, global_conditioning)
423
+ stats = self.conv_proj(inputs) * padding_mask
424
+ mean, log_stddev = torch.split(stats, self.out_channels, dim=1)
425
+ sampled = (mean + torch.randn_like(mean) * torch.exp(log_stddev)) * padding_mask
426
+ return sampled, mean, log_stddev
427
+
428
+
429
+ # Copied from transformers.models.speecht5.modeling_speecht5.HifiGanResidualBlock
430
+ class HifiGanResidualBlock(nn.Module):
431
+ def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5), leaky_relu_slope=0.1):
432
+ super().__init__()
433
+ self.leaky_relu_slope = leaky_relu_slope
434
+
435
+ self.convs1 = nn.ModuleList(
436
+ [
437
+ nn.Conv1d(
438
+ channels,
439
+ channels,
440
+ kernel_size,
441
+ stride=1,
442
+ dilation=dilation[i],
443
+ padding=self.get_padding(kernel_size, dilation[i]),
444
+ )
445
+ for i in range(len(dilation))
446
+ ]
447
+ )
448
+ self.convs2 = nn.ModuleList(
449
+ [
450
+ nn.Conv1d(
451
+ channels,
452
+ channels,
453
+ kernel_size,
454
+ stride=1,
455
+ dilation=1,
456
+ padding=self.get_padding(kernel_size, 1),
457
+ )
458
+ for _ in range(len(dilation))
459
+ ]
460
+ )
461
+
462
+ def get_padding(self, kernel_size, dilation=1):
463
+ return (kernel_size * dilation - dilation) // 2
464
+
465
+ def apply_weight_norm(self):
466
+ weight_norm = nn.utils.weight_norm
467
+ if hasattr(nn.utils.parametrizations, "weight_norm"):
468
+ weight_norm = nn.utils.parametrizations.weight_norm
469
+
470
+ for layer in self.convs1:
471
+ weight_norm(layer)
472
+ for layer in self.convs2:
473
+ weight_norm(layer)
474
+
475
+ def remove_weight_norm(self):
476
+ for layer in self.convs1:
477
+ nn.utils.remove_weight_norm(layer)
478
+ for layer in self.convs2:
479
+ nn.utils.remove_weight_norm(layer)
480
+
481
+ def forward(self, hidden_states):
482
+ for conv1, conv2 in zip(self.convs1, self.convs2):
483
+ residual = hidden_states
484
+ hidden_states = nn.functional.leaky_relu(hidden_states, self.leaky_relu_slope)
485
+ hidden_states = conv1(hidden_states)
486
+ hidden_states = nn.functional.leaky_relu(hidden_states, self.leaky_relu_slope)
487
+ hidden_states = conv2(hidden_states)
488
+ hidden_states = hidden_states + residual
489
+ return hidden_states
490
+
491
+
492
+ class VitsHifiGan(nn.Module):
493
+ def __init__(self, config: VitsConfig):
494
+ super().__init__()
495
+ self.config = config
496
+ self.num_kernels = len(config.resblock_kernel_sizes)
497
+ self.num_upsamples = len(config.upsample_rates)
498
+ self.conv_pre = nn.Conv1d(
499
+ config.flow_size,
500
+ config.upsample_initial_channel,
501
+ kernel_size=7,
502
+ stride=1,
503
+ padding=3,
504
+ )
505
+
506
+ self.upsampler = nn.ModuleList()
507
+ for i, (upsample_rate, kernel_size) in enumerate(zip(config.upsample_rates, config.upsample_kernel_sizes)):
508
+ self.upsampler.append(
509
+ nn.ConvTranspose1d(
510
+ config.upsample_initial_channel // (2**i),
511
+ config.upsample_initial_channel // (2 ** (i + 1)),
512
+ kernel_size=kernel_size,
513
+ stride=upsample_rate,
514
+ padding=(kernel_size - upsample_rate) // 2,
515
+ )
516
+ )
517
+
518
+ self.resblocks = nn.ModuleList()
519
+ for i in range(len(self.upsampler)):
520
+ channels = config.upsample_initial_channel // (2 ** (i + 1))
521
+ for kernel_size, dilation in zip(config.resblock_kernel_sizes, config.resblock_dilation_sizes):
522
+ self.resblocks.append(HifiGanResidualBlock(channels, kernel_size, dilation, config.leaky_relu_slope))
523
+
524
+ self.conv_post = nn.Conv1d(channels, 1, kernel_size=7, stride=1, padding=3, bias=False)
525
+
526
+ if config.speaker_embedding_size != 0:
527
+ self.cond = nn.Conv1d(config.speaker_embedding_size, config.upsample_initial_channel, 1)
528
+
529
+ def apply_weight_norm(self):
530
+ weight_norm = nn.utils.weight_norm
531
+ if hasattr(nn.utils.parametrizations, "weight_norm"):
532
+ weight_norm = nn.utils.parametrizations.weight_norm
533
+
534
+ for layer in self.upsampler:
535
+ weight_norm(layer)
536
+ for layer in self.resblocks:
537
+ layer.apply_weight_norm()
538
+
539
+ def remove_weight_norm(self):
540
+ for layer in self.upsampler:
541
+ nn.utils.remove_weight_norm(layer)
542
+ for layer in self.resblocks:
543
+ layer.remove_weight_norm()
544
+
545
+ def forward(
546
+ self, spectrogram: torch.FloatTensor, global_conditioning: Optional[torch.FloatTensor] = None
547
+ ) -> torch.FloatTensor:
548
+ r"""
549
+ Converts a spectrogram into a speech waveform.
550
+
551
+ Args:
552
+ spectrogram (`torch.FloatTensor` of shape `(batch_size, config.spectrogram_bins, sequence_length)`):
553
+ Tensor containing the spectrograms.
554
+ global_conditioning (`torch.FloatTensor` of shape `(batch_size, config.speaker_embedding_size, 1)`, *optional*):
555
+ Tensor containing speaker embeddings, for multispeaker models.
556
+
557
+ Returns:
558
+ `torch.FloatTensor`: Tensor of shape shape `(batch_size, 1, num_frames)` containing the speech waveform.
559
+ """
560
+ hidden_states = self.conv_pre(spectrogram)
561
+
562
+ if global_conditioning is not None:
563
+ hidden_states = hidden_states + self.cond(global_conditioning)
564
+
565
+ for i in range(self.num_upsamples):
566
+ hidden_states = nn.functional.leaky_relu(hidden_states, self.config.leaky_relu_slope)
567
+ hidden_states = self.upsampler[i](hidden_states)
568
+
569
+ res_state = self.resblocks[i * self.num_kernels](hidden_states)
570
+ for j in range(1, self.num_kernels):
571
+ res_state += self.resblocks[i * self.num_kernels + j](hidden_states)
572
+ hidden_states = res_state / self.num_kernels
573
+
574
+ hidden_states = nn.functional.leaky_relu(hidden_states)
575
+ hidden_states = self.conv_post(hidden_states)
576
+ waveform = torch.tanh(hidden_states)
577
+ return waveform
578
+
579
+
580
+ class VitsISTFT(nn.Module):
581
+ def __init__(self, config: VitsConfig):
582
+ super().__init__()
583
+ self.config = config
584
+ self.gen_istft_n_fft = config.gen_istft_n_fft
585
+ self.gen_istft_hop_size = config.gen_istft_hop_size
586
+ self.post_n_fft = config.gen_istft_n_fft
587
+
588
+ if config.istft_decoder in ["ms_istft", "mb_istft"]:
589
+ self.subbands = config.subbands
590
+ if config.istft_decoder == "mb_istft":
591
+ self.pqmf = PQMF(subbands=self.subbands)
592
+ else:
593
+ updown_filter = torch.zeros((self.subbands, self.subbands, self.subbands)).float()
594
+ for k in range(self.subbands):
595
+ updown_filter[k, k, 0] = 1.0
596
+ self.register_buffer("updown_filter", updown_filter)
597
+
598
+ self.multistream_conv_post = nn.Conv1d(
599
+ 4, 1, kernel_size=63, bias=False, padding=self.get_padding(63, 1)
600
+ )
601
+
602
+ self.num_kernels = len(config.resblock_kernel_sizes)
603
+ self.num_upsamples = len(config.upsample_rates)
604
+ self.conv_pre = nn.Conv1d(
605
+ config.flow_size,
606
+ config.upsample_initial_channel,
607
+ kernel_size=7,
608
+ stride=1,
609
+ padding=3,
610
+ )
611
+
612
+ self.upsampler = nn.ModuleList()
613
+ for i, (upsample_rate, kernel_size) in enumerate(zip(config.upsample_rates, config.upsample_kernel_sizes)):
614
+ self.upsampler.append(
615
+ nn.ConvTranspose1d(
616
+ config.upsample_initial_channel // (2**i),
617
+ config.upsample_initial_channel // (2 ** (i + 1)),
618
+ kernel_size=kernel_size,
619
+ stride=upsample_rate,
620
+ padding=(kernel_size - upsample_rate) // 2,
621
+ )
622
+ )
623
+
624
+ self.resblocks = nn.ModuleList()
625
+ for i in range(len(self.upsampler)):
626
+ channels = config.upsample_initial_channel // (2 ** (i + 1))
627
+ for kernel_size, dilation in zip(config.resblock_kernel_sizes, config.resblock_dilation_sizes):
628
+ self.resblocks.append(HifiGanResidualBlock(channels, kernel_size, dilation, config.leaky_relu_slope))
629
+
630
+ if config.istft_decoder == "istft":
631
+ self.conv_post = nn.Conv1d(channels, self.post_n_fft + 2, kernel_size=7, stride=1, padding=3, bias=True)
632
+ elif config.istft_decoder in ["ms_istft", "mb_istft"]:
633
+ self.conv_post = nn.Conv1d(
634
+ channels, self.subbands * (self.post_n_fft + 2), kernel_size=7, stride=1, padding=3, bias=True
635
+ )
636
+
637
+ self.reflection_pad = nn.ReflectionPad1d((1, 0))
638
+ self.stft = TorchSTFT(
639
+ filter_length=self.gen_istft_n_fft, hop_length=self.gen_istft_hop_size, win_length=self.gen_istft_n_fft
640
+ )
641
+
642
+ if config.speaker_embedding_size != 0:
643
+ self.cond = nn.Conv1d(config.speaker_embedding_size, config.upsample_initial_channel, 1)
644
+
645
+ def get_padding(self, kernel_size, dilation=1):
646
+ return int((kernel_size * dilation - dilation) / 2)
647
+
648
+ def apply_weight_norm(self):
649
+ weight_norm = nn.utils.weight_norm
650
+ if hasattr(nn.utils.parametrizations, "weight_norm"):
651
+ weight_norm = nn.utils.parametrizations.weight_norm
652
+
653
+ for layer in self.upsampler:
654
+ weight_norm(layer)
655
+ for layer in self.resblocks:
656
+ layer.apply_weight_norm()
657
+ weight_norm(self.conv_pre)
658
+ weight_norm(self.conv_post)
659
+
660
+ if self.config.istft_decoder == "ms_istft":
661
+ weight_norm(self.multistream_conv_post)
662
+
663
+ def remove_weight_norm(self):
664
+ for layer in self.upsampler:
665
+ nn.utils.remove_weight_norm(layer)
666
+ for layer in self.resblocks:
667
+ layer.remove_weight_norm()
668
+ nn.utils.remove_weight_norm(self.conv_pre)
669
+ nn.utils.remove_weight_norm(self.conv_post)
670
+
671
+ if self.config.istft_decoder == "ms_istft":
672
+ nn.utils.remove_weight_norm(self.multistream_conv_post)
673
+
674
+ def forward(
675
+ self, spectrogram: torch.FloatTensor, global_conditioning: Optional[torch.FloatTensor] = None
676
+ ) -> torch.FloatTensor:
677
+ r"""
678
+ Converts a spectrogram into a speech waveform.
679
+
680
+ Args:
681
+ spectrogram (`torch.FloatTensor` of shape `(batch_size, config.spectrogram_bins, sequence_length)`):
682
+ Tensor containing the spectrograms.
683
+ global_conditioning (`torch.FloatTensor` of shape `(batch_size, config.speaker_embedding_size, 1)`, *optional*):
684
+ Tensor containing speaker embeddings, for multispeaker models.
685
+
686
+ Returns:
687
+ `torch.FloatTensor`: Tensor of shape shape `(batch_size, 1, num_frames)` containing the speech waveform.
688
+ """
689
+ hidden_states = self.conv_pre(spectrogram)
690
+
691
+ if global_conditioning is not None:
692
+ hidden_states = hidden_states + self.cond(global_conditioning)
693
+
694
+ for i in range(self.num_upsamples):
695
+ hidden_states = nn.functional.leaky_relu(hidden_states, self.config.leaky_relu_slope)
696
+ hidden_states = self.upsampler[i](hidden_states)
697
+
698
+ res_state = self.resblocks[i * self.num_kernels](hidden_states)
699
+ for j in range(1, self.num_kernels):
700
+ res_state += self.resblocks[i * self.num_kernels + j](hidden_states)
701
+ hidden_states = res_state / self.num_kernels
702
+
703
+ hidden_states = nn.functional.leaky_relu(hidden_states)
704
+ hidden_states = self.reflection_pad(hidden_states)
705
+ hidden_states = self.conv_post(hidden_states)
706
+
707
+ if self.config.istft_decoder == "istft":
708
+ spec = torch.exp(hidden_states[:, : self.post_n_fft // 2 + 1, :])
709
+ phase = math.pi * torch.sin(hidden_states[:, self.post_n_fft // 2 + 1 :, :])
710
+ waveform = self.stft.inverse(spec, phase)
711
+
712
+ elif self.config.istft_decoder in ["mb_istft", "ms_istft"]:
713
+ hidden_states = torch.reshape(
714
+ hidden_states,
715
+ (
716
+ hidden_states.shape[0],
717
+ self.subbands,
718
+ hidden_states.shape[1] // self.subbands,
719
+ hidden_states.shape[-1],
720
+ ),
721
+ )
722
+ spec = torch.exp(hidden_states[:, :, : self.post_n_fft // 2 + 1, :])
723
+ phase = math.pi * torch.sin(hidden_states[:, :, self.post_n_fft // 2 + 1 :, :])
724
+
725
+ waveform_mb = self.stft.inverse(
726
+ torch.reshape(spec, (spec.shape[0] * self.subbands, self.gen_istft_n_fft // 2 + 1, spec.shape[-1])),
727
+ torch.reshape(phase, (phase.shape[0] * self.subbands, self.gen_istft_n_fft // 2 + 1, phase.shape[-1])),
728
+ )
729
+ waveform_mb = torch.reshape(waveform_mb, (hidden_states.shape[0], self.subbands, 1, waveform_mb.shape[-1]))
730
+ waveform_mb = waveform_mb.squeeze(-2)
731
+
732
+ if self.config.istft_decoder == "mb_istft":
733
+ waveform = self.pqmf.synthesis(waveform_mb)
734
+ else:
735
+ waveform_mb = torch.nn.functional.conv_transpose1d(
736
+ waveform_mb, self.updown_filter * self.subbands, stride=self.subbands
737
+ )
738
+ waveform = self.multistream_conv_post(waveform_mb)
739
+
740
+ return waveform
741
+
742
+
743
+ class PQMF(torch.nn.Module):
744
+ """PQMF module.
745
+ This module is based on `Near-perfect-reconstruction pseudo-QMF banks`_.
746
+ .. _`Near-perfect-reconstruction pseudo-QMF banks`:
747
+ https://ieeexplore.ieee.org/document/258122
748
+ """
749
+
750
+ def __init__(self, subbands=4, taps=62, cutoff_ratio=0.15, beta=9.0):
751
+ """Initilize PQMF module.
752
+ Args:
753
+ subbands (int): The number of subbands.
754
+ taps (int): The number of filter taps.
755
+ cutoff_ratio (float): Cut-off frequency ratio.
756
+ beta (float): Beta coefficient for kaiser window.
757
+ """
758
+ super(PQMF, self).__init__()
759
+
760
+ # define filter coefficient
761
+ h_proto = self.design_prototype_filter(taps, cutoff_ratio, beta)
762
+ h_analysis = np.zeros((subbands, len(h_proto)))
763
+ h_synthesis = np.zeros((subbands, len(h_proto)))
764
+ for k in range(subbands):
765
+ h_analysis[k] = (
766
+ 2
767
+ * h_proto
768
+ * np.cos(
769
+ (2 * k + 1) * (np.pi / (2 * subbands)) * (np.arange(taps + 1) - ((taps - 1) / 2))
770
+ + (-1) ** k * np.pi / 4
771
+ )
772
+ )
773
+ h_synthesis[k] = (
774
+ 2
775
+ * h_proto
776
+ * np.cos(
777
+ (2 * k + 1) * (np.pi / (2 * subbands)) * (np.arange(taps + 1) - ((taps - 1) / 2))
778
+ - (-1) ** k * np.pi / 4
779
+ )
780
+ )
781
+
782
+ # convert to tensor
783
+ analysis_filter = torch.from_numpy(h_analysis).float().unsqueeze(1)
784
+ synthesis_filter = torch.from_numpy(h_synthesis).float().unsqueeze(0)
785
+
786
+ # register coefficients as beffer
787
+ self.register_buffer("analysis_filter", analysis_filter)
788
+ self.register_buffer("synthesis_filter", synthesis_filter)
789
+
790
+ # filter for downsampling & upsampling
791
+ updown_filter = torch.zeros((subbands, subbands, subbands)).float()
792
+ for k in range(subbands):
793
+ updown_filter[k, k, 0] = 1.0
794
+ self.register_buffer("updown_filter", updown_filter)
795
+ self.subbands = subbands
796
+
797
+ # keep padding info
798
+ self.pad_fn = torch.nn.ConstantPad1d(taps // 2, 0.0)
799
+
800
+ def design_prototype_filter(self, taps=62, cutoff_ratio=0.15, beta=9.0):
801
+ """Design prototype filter for PQMF.
802
+ This method is based on `A Kaiser window approach for the design of prototype
803
+ filters of cosine modulated filterbanks`_.
804
+ Args:
805
+ taps (int): The number of filter taps.
806
+ cutoff_ratio (float): Cut-off frequency ratio.
807
+ beta (float): Beta coefficient for kaiser window.
808
+ Returns:
809
+ ndarray: Impluse response of prototype filter (taps + 1,).
810
+ .. _`A Kaiser window approach for the design of prototype filters of cosine modulated filterbanks`:
811
+ https://ieeexplore.ieee.org/abstract/document/681427
812
+ """
813
+ # check the arguments are valid
814
+ assert taps % 2 == 0, "The number of taps mush be even number."
815
+ assert 0.0 < cutoff_ratio < 1.0, "Cutoff ratio must be > 0.0 and < 1.0."
816
+
817
+ # make initial filter
818
+ omega_c = np.pi * cutoff_ratio
819
+ with np.errstate(invalid="ignore"):
820
+ h_i = np.sin(omega_c * (np.arange(taps + 1) - 0.5 * taps)) / (np.pi * (np.arange(taps + 1) - 0.5 * taps))
821
+ h_i[taps // 2] = np.cos(0) * cutoff_ratio # fix nan due to indeterminate form
822
+
823
+ # apply kaiser window
824
+ w = kaiser(taps + 1, beta)
825
+ h = h_i * w
826
+
827
+ return h
828
+
829
+ def analysis(self, x):
830
+ """Analysis with PQMF.
831
+ Args:
832
+ x (Tensor): Input tensor (B, 1, T).
833
+ Returns:
834
+ Tensor: Output tensor (B, subbands, T // subbands).
835
+ """
836
+ x = torch.nn.functional.conv1d(self.pad_fn(x), self.analysis_filter)
837
+ return torch.nn.functional.conv1d(x, self.updown_filter, stride=self.subbands)
838
+
839
+ def synthesis(self, x):
840
+ """Synthesis with PQMF.
841
+ Args:
842
+ x (Tensor): Input tensor (B, subbands, T // subbands).
843
+ Returns:
844
+ Tensor: Output tensor (B, 1, T).
845
+ """
846
+ # NOTE(kan-bayashi): Power will be dreased so here multipy by # subbands.
847
+ # Not sure this is the correct way, it is better to check again.
848
+ # TODO(kan-bayashi): Understand the reconstruction procedure
849
+ x = torch.nn.functional.conv_transpose1d(x, self.updown_filter * self.subbands, stride=self.subbands)
850
+ return torch.nn.functional.conv1d(self.pad_fn(x), self.synthesis_filter)
851
+
852
+
853
+ class TorchSTFT(torch.nn.Module):
854
+ def __init__(self, filter_length=800, hop_length=200, win_length=800, window="hann"):
855
+ super().__init__()
856
+ self.filter_length = filter_length
857
+ self.hop_length = hop_length
858
+ self.win_length = win_length
859
+ self.window = torch.from_numpy(get_window(window, win_length, fftbins=True).astype(np.float32))
860
+
861
+ def transform(self, input_data):
862
+ forward_transform = torch.stft(
863
+ input_data, self.filter_length, self.hop_length, self.win_length, window=self.window, return_complex=True
864
+ )
865
+
866
+ return torch.abs(forward_transform), torch.angle(forward_transform)
867
+
868
+ def inverse(self, magnitude, phase):
869
+ inverse_transform = torch.istft(
870
+ magnitude * torch.exp(phase * 1j),
871
+ self.filter_length,
872
+ self.hop_length,
873
+ self.win_length,
874
+ window=self.window.to(magnitude.device),
875
+ )
876
+
877
+ return inverse_transform.unsqueeze(-2) # unsqueeze to stay consistent with conv_transpose1d implementation
878
+
879
+ def forward(self, input_data):
880
+ self.magnitude, self.phase = self.transform(input_data)
881
+ reconstruction = self.inverse(self.magnitude, self.phase)
882
+ return reconstruction
883
+
884
+
885
+ class VitsResidualCouplingLayer(nn.Module):
886
+ def __init__(self, config: VitsConfig):
887
+ super().__init__()
888
+ self.half_channels = config.flow_size // 2
889
+
890
+ self.conv_pre = nn.Conv1d(self.half_channels, config.hidden_size, 1)
891
+ self.wavenet = VitsWaveNet(config, num_layers=config.prior_encoder_num_wavenet_layers)
892
+ self.conv_post = nn.Conv1d(config.hidden_size, self.half_channels, 1)
893
+
894
+ def forward(self, inputs, padding_mask, global_conditioning=None, reverse=False):
895
+ first_half, second_half = torch.split(inputs, [self.half_channels] * 2, dim=1)
896
+ hidden_states = self.conv_pre(first_half) * padding_mask
897
+ hidden_states = self.wavenet(hidden_states, padding_mask, global_conditioning)
898
+ mean = self.conv_post(hidden_states) * padding_mask
899
+ log_stddev = torch.zeros_like(mean)
900
+
901
+ if not reverse:
902
+ second_half = mean + second_half * torch.exp(log_stddev) * padding_mask
903
+ outputs = torch.cat([first_half, second_half], dim=1)
904
+ log_determinant = torch.sum(log_stddev, [1, 2])
905
+ return outputs, log_determinant
906
+ else:
907
+ second_half = (second_half - mean) * torch.exp(-log_stddev) * padding_mask
908
+ outputs = torch.cat([first_half, second_half], dim=1)
909
+ return outputs, None
910
+
911
+
912
+ class VitsResidualCouplingBlock(nn.Module):
913
+ def __init__(self, config: VitsConfig):
914
+ super().__init__()
915
+ self.flows = nn.ModuleList()
916
+ for _ in range(config.prior_encoder_num_flows):
917
+ self.flows.append(VitsResidualCouplingLayer(config))
918
+
919
+ def forward(self, inputs, padding_mask, global_conditioning=None, reverse=False):
920
+ if not reverse:
921
+ for flow in self.flows:
922
+ inputs, _ = flow(inputs, padding_mask, global_conditioning)
923
+ inputs = torch.flip(inputs, [1])
924
+ else:
925
+ for flow in reversed(self.flows):
926
+ inputs = torch.flip(inputs, [1])
927
+ inputs, _ = flow(inputs, padding_mask, global_conditioning, reverse=True)
928
+ return inputs
929
+
930
+
931
+ class VitsDilatedDepthSeparableConv(nn.Module):
932
+ def __init__(self, config: VitsConfig, dropout_rate=0.0):
933
+ super().__init__()
934
+ kernel_size = config.duration_predictor_kernel_size
935
+ channels = config.hidden_size
936
+ self.num_layers = config.depth_separable_num_layers
937
+
938
+ self.dropout = nn.Dropout(dropout_rate)
939
+ self.convs_dilated = nn.ModuleList()
940
+ self.convs_pointwise = nn.ModuleList()
941
+ self.norms_1 = nn.ModuleList()
942
+ self.norms_2 = nn.ModuleList()
943
+ for i in range(self.num_layers):
944
+ dilation = kernel_size**i
945
+ padding = (kernel_size * dilation - dilation) // 2
946
+ self.convs_dilated.append(
947
+ nn.Conv1d(
948
+ in_channels=channels,
949
+ out_channels=channels,
950
+ kernel_size=kernel_size,
951
+ groups=channels,
952
+ dilation=dilation,
953
+ padding=padding,
954
+ )
955
+ )
956
+ self.convs_pointwise.append(nn.Conv1d(channels, channels, 1))
957
+ self.norms_1.append(nn.LayerNorm(channels))
958
+ self.norms_2.append(nn.LayerNorm(channels))
959
+
960
+ def forward(self, inputs, padding_mask, global_conditioning=None):
961
+ if global_conditioning is not None:
962
+ inputs = inputs + global_conditioning
963
+
964
+ for i in range(self.num_layers):
965
+ hidden_states = self.convs_dilated[i](inputs * padding_mask)
966
+ hidden_states = self.norms_1[i](hidden_states.transpose(1, -1)).transpose(1, -1)
967
+ hidden_states = nn.functional.gelu(hidden_states)
968
+ hidden_states = self.convs_pointwise[i](hidden_states)
969
+ hidden_states = self.norms_2[i](hidden_states.transpose(1, -1)).transpose(1, -1)
970
+ hidden_states = nn.functional.gelu(hidden_states)
971
+ hidden_states = self.dropout(hidden_states)
972
+ inputs = inputs + hidden_states
973
+
974
+ return inputs * padding_mask
975
+
976
+
977
+ class VitsConvFlow(nn.Module):
978
+ def __init__(self, config: VitsConfig):
979
+ super().__init__()
980
+ self.filter_channels = config.hidden_size
981
+ self.half_channels = config.depth_separable_channels // 2
982
+ self.num_bins = config.duration_predictor_flow_bins
983
+ self.tail_bound = config.duration_predictor_tail_bound
984
+
985
+ self.conv_pre = nn.Conv1d(self.half_channels, self.filter_channels, 1)
986
+ self.conv_dds = VitsDilatedDepthSeparableConv(config)
987
+ self.conv_proj = nn.Conv1d(self.filter_channels, self.half_channels * (self.num_bins * 3 - 1), 1)
988
+
989
+ def forward(self, inputs, padding_mask, global_conditioning=None, reverse=False):
990
+ first_half, second_half = torch.split(inputs, [self.half_channels] * 2, dim=1)
991
+
992
+ hidden_states = self.conv_pre(first_half)
993
+ hidden_states = self.conv_dds(hidden_states, padding_mask, global_conditioning)
994
+ hidden_states = self.conv_proj(hidden_states) * padding_mask
995
+
996
+ batch_size, channels, length = first_half.shape
997
+ hidden_states = hidden_states.reshape(batch_size, channels, -1, length).permute(0, 1, 3, 2)
998
+
999
+ unnormalized_widths = hidden_states[..., : self.num_bins] / math.sqrt(self.filter_channels)
1000
+ unnormalized_heights = hidden_states[..., self.num_bins : 2 * self.num_bins] / math.sqrt(self.filter_channels)
1001
+ unnormalized_derivatives = hidden_states[..., 2 * self.num_bins :]
1002
+
1003
+ second_half, log_abs_det = _unconstrained_rational_quadratic_spline(
1004
+ second_half,
1005
+ unnormalized_widths,
1006
+ unnormalized_heights,
1007
+ unnormalized_derivatives,
1008
+ reverse=reverse,
1009
+ tail_bound=self.tail_bound,
1010
+ )
1011
+
1012
+ outputs = torch.cat([first_half, second_half], dim=1) * padding_mask
1013
+ if not reverse:
1014
+ log_determinant = torch.sum(log_abs_det * padding_mask, [1, 2])
1015
+ return outputs, log_determinant
1016
+ else:
1017
+ return outputs, None
1018
+
1019
+
1020
+ class VitsElementwiseAffine(nn.Module):
1021
+ def __init__(self, config: VitsConfig):
1022
+ super().__init__()
1023
+ self.channels = config.depth_separable_channels
1024
+ self.translate = nn.Parameter(torch.zeros(self.channels, 1))
1025
+ self.log_scale = nn.Parameter(torch.zeros(self.channels, 1))
1026
+
1027
+ def forward(self, inputs, padding_mask, global_conditioning=None, reverse=False):
1028
+ if not reverse:
1029
+ outputs = self.translate + torch.exp(self.log_scale) * inputs
1030
+ outputs = outputs * padding_mask
1031
+ log_determinant = torch.sum(self.log_scale * padding_mask, [1, 2])
1032
+ return outputs, log_determinant
1033
+ else:
1034
+ outputs = (inputs - self.translate) * torch.exp(-self.log_scale) * padding_mask
1035
+ return outputs, None
1036
+
1037
+
1038
+ class VitsStochasticDurationPredictor(nn.Module):
1039
+ def __init__(self, config):
1040
+ super().__init__()
1041
+ embed_dim = config.speaker_embedding_size
1042
+ filter_channels = config.hidden_size
1043
+
1044
+ self.conv_pre = nn.Conv1d(filter_channels, filter_channels, 1)
1045
+ self.conv_proj = nn.Conv1d(filter_channels, filter_channels, 1)
1046
+ self.conv_dds = VitsDilatedDepthSeparableConv(
1047
+ config,
1048
+ dropout_rate=config.duration_predictor_dropout,
1049
+ )
1050
+
1051
+ if embed_dim != 0:
1052
+ self.cond = nn.Conv1d(embed_dim, filter_channels, 1)
1053
+
1054
+ self.flows = nn.ModuleList()
1055
+ self.flows.append(VitsElementwiseAffine(config))
1056
+ for _ in range(config.duration_predictor_num_flows):
1057
+ self.flows.append(VitsConvFlow(config))
1058
+
1059
+ self.post_conv_pre = nn.Conv1d(1, filter_channels, 1)
1060
+ self.post_conv_proj = nn.Conv1d(filter_channels, filter_channels, 1)
1061
+ self.post_conv_dds = VitsDilatedDepthSeparableConv(
1062
+ config,
1063
+ dropout_rate=config.duration_predictor_dropout,
1064
+ )
1065
+
1066
+ self.post_flows = nn.ModuleList()
1067
+ self.post_flows.append(VitsElementwiseAffine(config))
1068
+ for _ in range(config.duration_predictor_num_flows):
1069
+ self.post_flows.append(VitsConvFlow(config))
1070
+
1071
+ def forward(self, inputs, padding_mask, global_conditioning=None, durations=None, reverse=False, noise_scale=1.0):
1072
+ inputs = torch.detach(inputs)
1073
+ inputs = self.conv_pre(inputs)
1074
+
1075
+ if global_conditioning is not None:
1076
+ global_conditioning = torch.detach(global_conditioning)
1077
+ inputs = inputs + self.cond(global_conditioning)
1078
+
1079
+ inputs = self.conv_dds(inputs, padding_mask)
1080
+ inputs = self.conv_proj(inputs) * padding_mask
1081
+
1082
+ if not reverse:
1083
+ hidden_states = self.post_conv_pre(durations)
1084
+ hidden_states = self.post_conv_dds(hidden_states, padding_mask)
1085
+ hidden_states = self.post_conv_proj(hidden_states) * padding_mask
1086
+
1087
+ random_posterior = (
1088
+ torch.randn(durations.size(0), 2, durations.size(2)).to(device=inputs.device, dtype=inputs.dtype)
1089
+ * padding_mask
1090
+ )
1091
+ log_determinant_posterior_sum = 0
1092
+ latents_posterior = random_posterior
1093
+ for flow in self.post_flows:
1094
+ latents_posterior, log_determinant = flow(
1095
+ latents_posterior, padding_mask, global_conditioning=inputs + hidden_states
1096
+ )
1097
+ latents_posterior = torch.flip(latents_posterior, [1])
1098
+ log_determinant_posterior_sum += log_determinant
1099
+
1100
+ first_half, second_half = torch.split(latents_posterior, [1, 1], dim=1)
1101
+
1102
+ log_determinant_posterior_sum += torch.sum(
1103
+ (nn.functional.logsigmoid(first_half) + nn.functional.logsigmoid(-first_half)) * padding_mask, [1, 2]
1104
+ )
1105
+ logq = (
1106
+ torch.sum(-0.5 * (math.log(2 * math.pi) + (random_posterior**2)) * padding_mask, [1, 2])
1107
+ - log_determinant_posterior_sum
1108
+ )
1109
+
1110
+ first_half = (durations - torch.sigmoid(first_half)) * padding_mask
1111
+ first_half = torch.log(torch.clamp_min(first_half, 1e-5)) * padding_mask
1112
+ log_determinant_sum = torch.sum(-first_half, [1, 2])
1113
+
1114
+ latents = torch.cat([first_half, second_half], dim=1)
1115
+ for flow in self.flows:
1116
+ latents, log_determinant = flow(latents, padding_mask, global_conditioning=inputs)
1117
+ latents = torch.flip(latents, [1])
1118
+ log_determinant_sum += log_determinant
1119
+
1120
+ nll = torch.sum(0.5 * (math.log(2 * math.pi) + (latents**2)) * padding_mask, [1, 2]) - log_determinant_sum
1121
+ return nll + logq
1122
+ else:
1123
+ flows = list(reversed(self.flows))
1124
+ flows = flows[:-2] + [flows[-1]] # remove a useless vflow
1125
+
1126
+ latents = (
1127
+ torch.randn(inputs.size(0), 2, inputs.size(2)).to(device=inputs.device, dtype=inputs.dtype)
1128
+ * noise_scale
1129
+ )
1130
+ for flow in flows:
1131
+ latents = torch.flip(latents, [1])
1132
+ latents, _ = flow(latents, padding_mask, global_conditioning=inputs, reverse=True)
1133
+
1134
+ log_duration, _ = torch.split(latents, [1, 1], dim=1)
1135
+ return log_duration
1136
+
1137
+
1138
+ class VitsDurationPredictor(nn.Module):
1139
+ def __init__(self, config):
1140
+ super().__init__()
1141
+ kernel_size = config.duration_predictor_kernel_size
1142
+ filter_channels = config.duration_predictor_filter_channels
1143
+
1144
+ self.dropout = nn.Dropout(config.duration_predictor_dropout)
1145
+ self.conv_1 = nn.Conv1d(config.hidden_size, filter_channels, kernel_size, padding=kernel_size // 2)
1146
+ self.norm_1 = nn.LayerNorm(filter_channels, eps=config.layer_norm_eps)
1147
+ self.conv_2 = nn.Conv1d(filter_channels, filter_channels, kernel_size, padding=kernel_size // 2)
1148
+ self.norm_2 = nn.LayerNorm(filter_channels, eps=config.layer_norm_eps)
1149
+ self.proj = nn.Conv1d(filter_channels, 1, 1)
1150
+
1151
+ if config.speaker_embedding_size != 0:
1152
+ self.cond = nn.Conv1d(config.speaker_embedding_size, config.hidden_size, 1)
1153
+
1154
+ def forward(self, inputs, padding_mask, global_conditioning=None):
1155
+ inputs = torch.detach(inputs)
1156
+
1157
+ if global_conditioning is not None:
1158
+ global_conditioning = torch.detach(global_conditioning)
1159
+ inputs = inputs + self.cond(global_conditioning)
1160
+
1161
+ inputs = self.conv_1(inputs * padding_mask)
1162
+ inputs = torch.relu(inputs)
1163
+ inputs = self.norm_1(inputs.transpose(1, -1)).transpose(1, -1)
1164
+ inputs = self.dropout(inputs)
1165
+
1166
+ inputs = self.conv_2(inputs * padding_mask)
1167
+ inputs = torch.relu(inputs)
1168
+ inputs = self.norm_2(inputs.transpose(1, -1)).transpose(1, -1)
1169
+ inputs = self.dropout(inputs)
1170
+
1171
+ inputs = self.proj(inputs * padding_mask)
1172
+ return inputs * padding_mask
1173
+
1174
+
1175
+ class VitsAttention(nn.Module):
1176
+ """Multi-headed attention with relative positional representation."""
1177
+
1178
+ def __init__(self, config: VitsConfig):
1179
+ super().__init__()
1180
+ self.embed_dim = config.hidden_size
1181
+ self.num_heads = config.num_attention_heads
1182
+ self.dropout = config.attention_dropout
1183
+ self.window_size = config.window_size
1184
+
1185
+ self.head_dim = self.embed_dim // self.num_heads
1186
+ self.scaling = self.head_dim**-0.5
1187
+
1188
+ if (self.head_dim * self.num_heads) != self.embed_dim:
1189
+ raise ValueError(
1190
+ f"hidden_size must be divisible by num_attention_heads (got `hidden_size`: {self.embed_dim}"
1191
+ f" and `num_attention_heads`: {self.num_heads})."
1192
+ )
1193
+
1194
+ self.k_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.use_bias)
1195
+ self.v_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.use_bias)
1196
+ self.q_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.use_bias)
1197
+ self.out_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.use_bias)
1198
+
1199
+ if self.window_size:
1200
+ self.emb_rel_k = nn.Parameter(torch.randn(1, self.window_size * 2 + 1, self.head_dim) * self.scaling)
1201
+ self.emb_rel_v = nn.Parameter(torch.randn(1, self.window_size * 2 + 1, self.head_dim) * self.scaling)
1202
+
1203
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
1204
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
1205
+
1206
+ def forward(
1207
+ self,
1208
+ hidden_states: torch.Tensor,
1209
+ key_value_states: Optional[torch.Tensor] = None,
1210
+ attention_mask: Optional[torch.Tensor] = None,
1211
+ layer_head_mask: Optional[torch.Tensor] = None,
1212
+ output_attentions: bool = False,
1213
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
1214
+ """Input shape: Batch x Time x Channel"""
1215
+
1216
+ # if key_value_states are provided this layer is used as a cross-attention layer
1217
+ # for the decoder
1218
+
1219
+ bsz, tgt_len, _ = hidden_states.size()
1220
+
1221
+ # get query proj
1222
+ query_states = self.q_proj(hidden_states) * self.scaling
1223
+
1224
+ # self_attention
1225
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
1226
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
1227
+
1228
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
1229
+ query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
1230
+ key_states = key_states.view(*proj_shape)
1231
+ value_states = value_states.view(*proj_shape)
1232
+
1233
+ src_len = key_states.size(1)
1234
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
1235
+
1236
+ if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
1237
+ raise ValueError(
1238
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
1239
+ f" {attn_weights.size()}"
1240
+ )
1241
+
1242
+ if self.window_size is not None:
1243
+ key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, src_len)
1244
+ relative_logits = torch.matmul(query_states, key_relative_embeddings.transpose(-2, -1))
1245
+ rel_pos_bias = self._relative_position_to_absolute_position(relative_logits)
1246
+ attn_weights += rel_pos_bias
1247
+
1248
+ if attention_mask is not None:
1249
+ if attention_mask.size() != (bsz, 1, tgt_len, src_len):
1250
+ raise ValueError(
1251
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
1252
+ )
1253
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
1254
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
1255
+
1256
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
1257
+
1258
+ if layer_head_mask is not None:
1259
+ if layer_head_mask.size() != (self.num_heads,):
1260
+ raise ValueError(
1261
+ f"Head mask for a single layer should be of size {(self.num_heads,)}, but is"
1262
+ f" {layer_head_mask.size()}"
1263
+ )
1264
+ attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
1265
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
1266
+
1267
+ if output_attentions:
1268
+ # this operation is a bit awkward, but it's required to
1269
+ # make sure that attn_weights keeps its gradient.
1270
+ # In order to do so, attn_weights have to be reshaped
1271
+ # twice and have to be reused in the following
1272
+ attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
1273
+ attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
1274
+ else:
1275
+ attn_weights_reshaped = None
1276
+
1277
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
1278
+
1279
+ attn_output = torch.bmm(attn_probs, value_states)
1280
+
1281
+ if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
1282
+ raise ValueError(
1283
+ f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
1284
+ f" {attn_output.size()}"
1285
+ )
1286
+
1287
+ if self.window_size is not None:
1288
+ value_relative_embeddings = self._get_relative_embeddings(self.emb_rel_v, src_len)
1289
+ relative_weights = self._absolute_position_to_relative_position(attn_probs)
1290
+ rel_pos_bias = torch.matmul(relative_weights, value_relative_embeddings)
1291
+ attn_output += rel_pos_bias
1292
+
1293
+ attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
1294
+ attn_output = attn_output.transpose(1, 2)
1295
+
1296
+ # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
1297
+ # partitioned aross GPUs when using tensor-parallelism.
1298
+ attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
1299
+
1300
+ attn_output = self.out_proj(attn_output)
1301
+
1302
+ return attn_output, attn_weights_reshaped
1303
+
1304
+ def _get_relative_embeddings(self, relative_embeddings, length):
1305
+ pad_length = max(length - (self.window_size + 1), 0)
1306
+ if pad_length > 0:
1307
+ relative_embeddings = nn.functional.pad(relative_embeddings, [0, 0, pad_length, pad_length, 0, 0])
1308
+
1309
+ slice_start_position = max((self.window_size + 1) - length, 0)
1310
+ slice_end_position = slice_start_position + 2 * length - 1
1311
+ return relative_embeddings[:, slice_start_position:slice_end_position]
1312
+
1313
+ def _relative_position_to_absolute_position(self, x):
1314
+ batch_heads, length, _ = x.size()
1315
+
1316
+ # Concat columns of pad to shift from relative to absolute indexing.
1317
+ x = nn.functional.pad(x, [0, 1, 0, 0, 0, 0])
1318
+
1319
+ # Concat extra elements so to add up to shape (len+1, 2*len-1).
1320
+ x_flat = x.view([batch_heads, length * 2 * length])
1321
+ x_flat = nn.functional.pad(x_flat, [0, length - 1, 0, 0])
1322
+
1323
+ # Reshape and slice out the padded elements.
1324
+ x_final = x_flat.view([batch_heads, length + 1, 2 * length - 1])
1325
+ x_final = x_final[:, :length, length - 1 :]
1326
+ return x_final
1327
+
1328
+ def _absolute_position_to_relative_position(self, x):
1329
+ batch_heads, length, _ = x.size()
1330
+
1331
+ # Pad along column
1332
+ x = nn.functional.pad(x, [0, length - 1, 0, 0, 0, 0])
1333
+ x_flat = x.view([batch_heads, length * (2 * length - 1)])
1334
+
1335
+ # Add 0's in the beginning that will skew the elements after reshape
1336
+ x_flat = nn.functional.pad(x_flat, [length, 0, 0, 0])
1337
+ x_final = x_flat.view([batch_heads, length, 2 * length])[:, :, 1:]
1338
+ return x_final
1339
+
1340
+
1341
+ class VitsFeedForward(nn.Module):
1342
+ def __init__(self, config):
1343
+ super().__init__()
1344
+ self.conv_1 = nn.Conv1d(config.hidden_size, config.ffn_dim, config.ffn_kernel_size)
1345
+ self.conv_2 = nn.Conv1d(config.ffn_dim, config.hidden_size, config.ffn_kernel_size)
1346
+ self.dropout = nn.Dropout(config.activation_dropout)
1347
+
1348
+ if isinstance(config.hidden_act, str):
1349
+ self.act_fn = ACT2FN[config.hidden_act]
1350
+ else:
1351
+ self.act_fn = config.hidden_act
1352
+
1353
+ if config.ffn_kernel_size > 1:
1354
+ pad_left = (config.ffn_kernel_size - 1) // 2
1355
+ pad_right = config.ffn_kernel_size // 2
1356
+ self.padding = [pad_left, pad_right, 0, 0, 0, 0]
1357
+ else:
1358
+ self.padding = None
1359
+
1360
+ def forward(self, hidden_states, padding_mask):
1361
+ hidden_states = hidden_states.permute(0, 2, 1)
1362
+ padding_mask = padding_mask.permute(0, 2, 1)
1363
+
1364
+ hidden_states = hidden_states * padding_mask
1365
+ if self.padding is not None:
1366
+ hidden_states = nn.functional.pad(hidden_states, self.padding)
1367
+
1368
+ hidden_states = self.conv_1(hidden_states)
1369
+ hidden_states = self.act_fn(hidden_states)
1370
+ hidden_states = self.dropout(hidden_states)
1371
+
1372
+ hidden_states = hidden_states * padding_mask
1373
+ if self.padding is not None:
1374
+ hidden_states = nn.functional.pad(hidden_states, self.padding)
1375
+
1376
+ hidden_states = self.conv_2(hidden_states)
1377
+ hidden_states = hidden_states * padding_mask
1378
+
1379
+ hidden_states = hidden_states.permute(0, 2, 1)
1380
+ return hidden_states
1381
+
1382
+
1383
+ class VitsEncoderLayer(nn.Module):
1384
+ def __init__(self, config: VitsConfig):
1385
+ super().__init__()
1386
+ self.attention = VitsAttention(config)
1387
+ self.dropout = nn.Dropout(config.hidden_dropout)
1388
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
1389
+ self.feed_forward = VitsFeedForward(config)
1390
+ self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
1391
+
1392
+ def forward(
1393
+ self,
1394
+ hidden_states: torch.Tensor,
1395
+ padding_mask: torch.FloatTensor,
1396
+ attention_mask: Optional[torch.Tensor] = None,
1397
+ output_attentions: bool = False,
1398
+ ):
1399
+ residual = hidden_states
1400
+ hidden_states, attn_weights = self.attention(
1401
+ hidden_states=hidden_states,
1402
+ attention_mask=attention_mask,
1403
+ output_attentions=output_attentions,
1404
+ )
1405
+
1406
+ hidden_states = self.dropout(hidden_states)
1407
+ hidden_states = self.layer_norm(residual + hidden_states)
1408
+
1409
+ residual = hidden_states
1410
+ hidden_states = self.feed_forward(hidden_states, padding_mask)
1411
+ hidden_states = self.dropout(hidden_states)
1412
+ hidden_states = self.final_layer_norm(residual + hidden_states)
1413
+
1414
+ outputs = (hidden_states,)
1415
+
1416
+ if output_attentions:
1417
+ outputs += (attn_weights,)
1418
+
1419
+ return outputs
1420
+
1421
+
1422
+ class VitsEncoder(nn.Module):
1423
+ def __init__(self, config: VitsConfig):
1424
+ super().__init__()
1425
+ self.config = config
1426
+ self.layers = nn.ModuleList([VitsEncoderLayer(config) for _ in range(config.num_hidden_layers)])
1427
+ self.gradient_checkpointing = False
1428
+ self.layerdrop = config.layerdrop
1429
+
1430
+ def forward(
1431
+ self,
1432
+ hidden_states: torch.FloatTensor,
1433
+ padding_mask: torch.FloatTensor,
1434
+ attention_mask: Optional[torch.Tensor] = None,
1435
+ output_attentions: Optional[bool] = None,
1436
+ output_hidden_states: Optional[bool] = None,
1437
+ return_dict: Optional[bool] = None,
1438
+ ) -> Union[Tuple, BaseModelOutput]:
1439
+ all_hidden_states = () if output_hidden_states else None
1440
+ all_self_attentions = () if output_attentions else None
1441
+
1442
+ # expand attention_mask
1443
+ if attention_mask is not None:
1444
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
1445
+ attention_mask = _prepare_4d_attention_mask(attention_mask, hidden_states.dtype)
1446
+
1447
+ hidden_states = hidden_states * padding_mask
1448
+
1449
+ synced_gpus = is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)
1450
+
1451
+ for encoder_layer in self.layers:
1452
+ if output_hidden_states:
1453
+ all_hidden_states = all_hidden_states + (hidden_states,)
1454
+
1455
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
1456
+ dropout_probability = np.random.uniform(0, 1)
1457
+
1458
+ skip_the_layer = self.training and (dropout_probability < self.layerdrop)
1459
+ if not skip_the_layer or synced_gpus:
1460
+ # under fsdp or deepspeed zero3 all gpus must run in sync
1461
+ if self.gradient_checkpointing and self.training:
1462
+ layer_outputs = self._gradient_checkpointing_func(
1463
+ encoder_layer.__call__,
1464
+ hidden_states,
1465
+ padding_mask,
1466
+ attention_mask,
1467
+ output_attentions,
1468
+ )
1469
+ else:
1470
+ layer_outputs = encoder_layer(
1471
+ hidden_states,
1472
+ attention_mask=attention_mask,
1473
+ padding_mask=padding_mask,
1474
+ output_attentions=output_attentions,
1475
+ )
1476
+ hidden_states = layer_outputs[0]
1477
+
1478
+ if skip_the_layer:
1479
+ layer_outputs = (None, None)
1480
+
1481
+ if output_attentions:
1482
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
1483
+
1484
+ hidden_states = hidden_states * padding_mask
1485
+
1486
+ if output_hidden_states:
1487
+ all_hidden_states = all_hidden_states + (hidden_states,)
1488
+
1489
+ if not return_dict:
1490
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
1491
+
1492
+ return BaseModelOutput(
1493
+ last_hidden_state=hidden_states,
1494
+ hidden_states=all_hidden_states,
1495
+ attentions=all_self_attentions,
1496
+ )
1497
+
1498
+
1499
+ class VitsTextEncoder(nn.Module):
1500
+ """
1501
+ Transformer encoder that uses relative positional representation instead of absolute positional encoding.
1502
+ """
1503
+
1504
+ def __init__(self, config: VitsConfig):
1505
+ super().__init__()
1506
+ self.config = config
1507
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, config.pad_token_id)
1508
+ self.encoder = VitsEncoder(config)
1509
+ self.project = nn.Conv1d(config.hidden_size, config.flow_size * 2, kernel_size=1)
1510
+
1511
+ def get_input_embeddings(self):
1512
+ return self.embed_tokens
1513
+
1514
+ def set_input_embeddings(self, value):
1515
+ self.embed_tokens = value
1516
+
1517
+ def forward(
1518
+ self,
1519
+ input_ids: torch.Tensor,
1520
+ padding_mask: torch.FloatTensor,
1521
+ attention_mask: Optional[torch.Tensor] = None,
1522
+ output_attentions: Optional[bool] = None,
1523
+ output_hidden_states: Optional[bool] = None,
1524
+ return_dict: Optional[bool] = True,
1525
+ ) -> Union[Tuple[torch.Tensor], VitsTextEncoderOutput]:
1526
+ hidden_states = self.embed_tokens(input_ids) * math.sqrt(self.config.hidden_size)
1527
+
1528
+ encoder_outputs = self.encoder(
1529
+ hidden_states=hidden_states,
1530
+ padding_mask=padding_mask,
1531
+ attention_mask=attention_mask,
1532
+ output_attentions=output_attentions,
1533
+ output_hidden_states=output_hidden_states,
1534
+ return_dict=return_dict,
1535
+ )
1536
+
1537
+ last_hidden_state = encoder_outputs[0] if not return_dict else encoder_outputs.last_hidden_state
1538
+
1539
+ stats = self.project(last_hidden_state.transpose(1, 2)).transpose(1, 2) * padding_mask
1540
+ prior_means, prior_log_variances = torch.split(stats, self.config.flow_size, dim=2)
1541
+
1542
+ if not return_dict:
1543
+ outputs = (last_hidden_state, prior_means, prior_log_variances) + encoder_outputs[1:]
1544
+ return outputs
1545
+
1546
+ return VitsTextEncoderOutput(
1547
+ last_hidden_state=last_hidden_state,
1548
+ prior_means=prior_means,
1549
+ prior_log_variances=prior_log_variances,
1550
+ hidden_states=encoder_outputs.hidden_states,
1551
+ attentions=encoder_outputs.attentions,
1552
+ )
1553
+
1554
+
1555
+ class VitsPreTrainedModel(PreTrainedModel):
1556
+ """
1557
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
1558
+ models.
1559
+ """
1560
+
1561
+ config_class = VitsConfig
1562
+ base_model_prefix = "vits"
1563
+ main_input_name = "input_ids"
1564
+ supports_gradient_checkpointing = True
1565
+
1566
+ def _init_weights(self, module):
1567
+ """Initialize the weights"""
1568
+ if isinstance(module, nn.Linear):
1569
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
1570
+ if module.bias is not None:
1571
+ module.bias.data.zero_()
1572
+ elif isinstance(module, nn.LayerNorm):
1573
+ module.bias.data.zero_()
1574
+ module.weight.data.fill_(1.0)
1575
+ elif isinstance(module, nn.Conv1d):
1576
+ nn.init.kaiming_normal_(module.weight)
1577
+ if module.bias is not None:
1578
+ k = math.sqrt(module.groups / (module.in_channels * module.kernel_size[0]))
1579
+ nn.init.uniform_(module.bias, a=-k, b=k)
1580
+ elif isinstance(module, nn.Embedding):
1581
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
1582
+ if module.padding_idx is not None:
1583
+ module.weight.data[module.padding_idx].zero_()
1584
+
1585
+
1586
+ VITS_START_DOCSTRING = r"""
1587
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1588
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1589
+ etc.)
1590
+
1591
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1592
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1593
+ and behavior.
1594
+
1595
+ Parameters:
1596
+ config ([`VitsConfig`]):
1597
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
1598
+ load the weights associated with the model, only the configuration. Check out the
1599
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1600
+ """
1601
+
1602
+
1603
+ VITS_INPUTS_DOCSTRING = r"""
1604
+ Args:
1605
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1606
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1607
+ it.
1608
+
1609
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1610
+ [`PreTrainedTokenizer.__call__`] for details.
1611
+
1612
+ [What are input IDs?](../glossary#input-ids)
1613
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1614
+ Mask to avoid performing convolution and attention on padding token indices. Mask values selected in `[0,
1615
+ 1]`:
1616
+
1617
+ - 1 for tokens that are **not masked**,
1618
+ - 0 for tokens that are **masked**.
1619
+
1620
+ [What are attention masks?](../glossary#attention-mask)
1621
+ speaker_id (`int`, *optional*):
1622
+ Which speaker embedding to use. Only used for multispeaker models.
1623
+ output_attentions (`bool`, *optional*):
1624
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1625
+ tensors for more detail.
1626
+ output_hidden_states (`bool`, *optional*):
1627
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1628
+ more detail.
1629
+ return_dict (`bool`, *optional*):
1630
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1631
+ """
1632
+
1633
+
1634
+ @add_start_docstrings(
1635
+ "The complete VITS model, for text-to-speech synthesis.",
1636
+ VITS_START_DOCSTRING,
1637
+ )
1638
+ class VitsModel(VitsPreTrainedModel):
1639
+ def __init__(self, config: VitsConfig):
1640
+ super().__init__(config)
1641
+ self.config = config
1642
+ self.text_encoder = VitsTextEncoder(config)
1643
+ self.flow = VitsResidualCouplingBlock(config)
1644
+
1645
+ if config.istft_decoder in ["istft", "mb_istft", "ms_istft"]:
1646
+ self.decoder = VitsISTFT(config)
1647
+ else:
1648
+ self.decoder = VitsHifiGan(config)
1649
+
1650
+ if config.use_stochastic_duration_prediction:
1651
+ self.duration_predictor = VitsStochasticDurationPredictor(config)
1652
+ else:
1653
+ self.duration_predictor = VitsDurationPredictor(config)
1654
+
1655
+ if config.num_speakers > 1:
1656
+ self.embed_speaker = nn.Embedding(config.num_speakers, config.speaker_embedding_size)
1657
+
1658
+ # This is used only for training.
1659
+ self.posterior_encoder = VitsPosteriorEncoder(config)
1660
+
1661
+ # These parameters control the synthesised speech properties
1662
+ self.speaking_rate = config.speaking_rate
1663
+ self.noise_scale = config.noise_scale
1664
+ self.noise_scale_duration = config.noise_scale_duration
1665
+
1666
+ # Initialize weights and apply final processing
1667
+ self.post_init()
1668
+
1669
+ def get_encoder(self):
1670
+ return self.text_encoder
1671
+
1672
+ @add_start_docstrings_to_model_forward(VITS_INPUTS_DOCSTRING)
1673
+ @replace_return_docstrings(output_type=VitsModelOutput, config_class=_CONFIG_FOR_DOC)
1674
+ def forward(
1675
+ self,
1676
+ input_ids: Optional[torch.Tensor] = None,
1677
+ attention_mask: Optional[torch.Tensor] = None,
1678
+ speaker_id: Optional[int] = None,
1679
+ output_attentions: Optional[bool] = None,
1680
+ output_hidden_states: Optional[bool] = None,
1681
+ return_dict: Optional[bool] = None,
1682
+ labels: Optional[torch.FloatTensor] = None,
1683
+ ) -> Union[Tuple[Any], VitsModelOutput]:
1684
+ r"""
1685
+ labels (`torch.FloatTensor` of shape `(batch_size, config.spectrogram_bins, sequence_length)`, *optional*):
1686
+ Float values of target spectrogram. Timesteps set to `-100.0` are ignored (masked) for the loss
1687
+ computation.
1688
+
1689
+ Returns:
1690
+
1691
+ Example:
1692
+
1693
+ ```python
1694
+ >>> from transformers import VitsTokenizer, VitsModel, set_seed
1695
+ >>> import torch
1696
+
1697
+ >>> tokenizer = VitsTokenizer.from_pretrained("facebook/mms-tts-eng")
1698
+ >>> model = VitsModel.from_pretrained("facebook/mms-tts-eng")
1699
+
1700
+ >>> inputs = tokenizer(text="Hello - my dog is cute", return_tensors="pt")
1701
+
1702
+ >>> set_seed(555) # make deterministic
1703
+
1704
+ >>> with torch.no_grad():
1705
+ ... outputs = model(inputs["input_ids"])
1706
+ >>> outputs.waveform.shape
1707
+ torch.Size([1, 45824])
1708
+ ```
1709
+ """
1710
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1711
+ output_hidden_states = (
1712
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1713
+ )
1714
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1715
+
1716
+ if labels is not None:
1717
+ raise NotImplementedError("Training of VITS is not supported yet.")
1718
+
1719
+ if attention_mask is not None:
1720
+ input_padding_mask = attention_mask.unsqueeze(-1).float()
1721
+ else:
1722
+ input_padding_mask = torch.ones_like(input_ids).unsqueeze(-1).float()
1723
+
1724
+ if self.config.num_speakers > 1 and speaker_id is not None:
1725
+ if not 0 <= speaker_id < self.config.num_speakers:
1726
+ raise ValueError(f"Set `speaker_id` in the range 0-{self.config.num_speakers - 1}.")
1727
+ if isinstance(speaker_id, int):
1728
+ speaker_id = torch.full(size=(1,), fill_value=speaker_id, device=self.device)
1729
+ speaker_embeddings = self.embed_speaker(speaker_id).unsqueeze(-1)
1730
+ else:
1731
+ speaker_embeddings = None
1732
+
1733
+ text_encoder_output = self.text_encoder(
1734
+ input_ids=input_ids,
1735
+ padding_mask=input_padding_mask,
1736
+ attention_mask=attention_mask,
1737
+ output_attentions=output_attentions,
1738
+ output_hidden_states=output_hidden_states,
1739
+ return_dict=return_dict,
1740
+ )
1741
+ hidden_states = text_encoder_output[0] if not return_dict else text_encoder_output.last_hidden_state
1742
+ hidden_states = hidden_states.transpose(1, 2)
1743
+ input_padding_mask = input_padding_mask.transpose(1, 2)
1744
+ prior_means = text_encoder_output[1] if not return_dict else text_encoder_output.prior_means
1745
+ prior_log_variances = text_encoder_output[2] if not return_dict else text_encoder_output.prior_log_variances
1746
+
1747
+ if self.config.use_stochastic_duration_prediction:
1748
+ log_duration = self.duration_predictor(
1749
+ hidden_states,
1750
+ input_padding_mask,
1751
+ speaker_embeddings,
1752
+ reverse=True,
1753
+ noise_scale=self.noise_scale_duration,
1754
+ )
1755
+ else:
1756
+ log_duration = self.duration_predictor(hidden_states, input_padding_mask, speaker_embeddings)
1757
+
1758
+ length_scale = 1.0 / self.speaking_rate
1759
+ duration = torch.ceil(torch.exp(log_duration) * input_padding_mask * length_scale)
1760
+ predicted_lengths = torch.clamp_min(torch.sum(duration, [1, 2]), 1).long()
1761
+
1762
+ # Create a padding mask for the output lengths of shape (batch, 1, max_output_length)
1763
+ indices = torch.arange(predicted_lengths.max(), dtype=predicted_lengths.dtype, device=predicted_lengths.device)
1764
+ output_padding_mask = indices.unsqueeze(0) < predicted_lengths.unsqueeze(1)
1765
+ output_padding_mask = output_padding_mask.unsqueeze(1).to(input_padding_mask.dtype)
1766
+
1767
+ # Reconstruct an attention tensor of shape (batch, 1, out_length, in_length)
1768
+ attn_mask = torch.unsqueeze(input_padding_mask, 2) * torch.unsqueeze(output_padding_mask, -1)
1769
+ batch_size, _, output_length, input_length = attn_mask.shape
1770
+ cum_duration = torch.cumsum(duration, -1).view(batch_size * input_length, 1)
1771
+ indices = torch.arange(output_length, dtype=duration.dtype, device=duration.device)
1772
+ valid_indices = indices.unsqueeze(0) < cum_duration
1773
+ valid_indices = valid_indices.to(attn_mask.dtype).view(batch_size, input_length, output_length)
1774
+ padded_indices = valid_indices - nn.functional.pad(valid_indices, [0, 0, 1, 0, 0, 0])[:, :-1]
1775
+ attn = padded_indices.unsqueeze(1).transpose(2, 3) * attn_mask
1776
+
1777
+ # Expand prior distribution
1778
+ prior_means = torch.matmul(attn.squeeze(1), prior_means).transpose(1, 2)
1779
+ prior_log_variances = torch.matmul(attn.squeeze(1), prior_log_variances).transpose(1, 2)
1780
+
1781
+ prior_latents = prior_means + torch.randn_like(prior_means) * torch.exp(prior_log_variances) * self.noise_scale
1782
+ latents = self.flow(prior_latents, output_padding_mask, speaker_embeddings, reverse=True)
1783
+
1784
+ spectrogram = latents * output_padding_mask
1785
+ waveform = self.decoder(spectrogram, speaker_embeddings)
1786
+ waveform = waveform.squeeze(1)
1787
+ sequence_lengths = predicted_lengths * np.prod(self.config.upsample_rates)
1788
+
1789
+ if not return_dict:
1790
+ outputs = (waveform, sequence_lengths, spectrogram) + text_encoder_output[3:]
1791
+ return outputs
1792
+
1793
+ return VitsModelOutput(
1794
+ waveform=waveform,
1795
+ sequence_lengths=sequence_lengths,
1796
+ spectrogram=spectrogram,
1797
+ hidden_states=text_encoder_output.hidden_states,
1798
+ attentions=text_encoder_output.attentions,
1799
+ )