torchaudio 2.9.0__cp314-cp314-macosx_11_0_arm64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of torchaudio might be problematic. Click here for more details.
- torchaudio/.dylibs/libc++.1.0.dylib +0 -0
- torchaudio/__init__.py +204 -0
- torchaudio/_extension/__init__.py +61 -0
- torchaudio/_extension/utils.py +133 -0
- torchaudio/_internal/__init__.py +10 -0
- torchaudio/_internal/module_utils.py +171 -0
- torchaudio/_torchcodec.py +340 -0
- torchaudio/compliance/__init__.py +5 -0
- torchaudio/compliance/kaldi.py +813 -0
- torchaudio/datasets/__init__.py +47 -0
- torchaudio/datasets/cmuarctic.py +157 -0
- torchaudio/datasets/cmudict.py +186 -0
- torchaudio/datasets/commonvoice.py +86 -0
- torchaudio/datasets/dr_vctk.py +121 -0
- torchaudio/datasets/fluentcommands.py +108 -0
- torchaudio/datasets/gtzan.py +1118 -0
- torchaudio/datasets/iemocap.py +147 -0
- torchaudio/datasets/librilight_limited.py +111 -0
- torchaudio/datasets/librimix.py +133 -0
- torchaudio/datasets/librispeech.py +174 -0
- torchaudio/datasets/librispeech_biasing.py +189 -0
- torchaudio/datasets/libritts.py +168 -0
- torchaudio/datasets/ljspeech.py +107 -0
- torchaudio/datasets/musdb_hq.py +139 -0
- torchaudio/datasets/quesst14.py +136 -0
- torchaudio/datasets/snips.py +157 -0
- torchaudio/datasets/speechcommands.py +183 -0
- torchaudio/datasets/tedlium.py +218 -0
- torchaudio/datasets/utils.py +54 -0
- torchaudio/datasets/vctk.py +143 -0
- torchaudio/datasets/voxceleb1.py +309 -0
- torchaudio/datasets/yesno.py +89 -0
- torchaudio/functional/__init__.py +130 -0
- torchaudio/functional/_alignment.py +128 -0
- torchaudio/functional/filtering.py +1685 -0
- torchaudio/functional/functional.py +2505 -0
- torchaudio/lib/__init__.py +0 -0
- torchaudio/lib/_torchaudio.so +0 -0
- torchaudio/lib/libtorchaudio.so +0 -0
- torchaudio/models/__init__.py +85 -0
- torchaudio/models/_hdemucs.py +1008 -0
- torchaudio/models/conformer.py +293 -0
- torchaudio/models/conv_tasnet.py +330 -0
- torchaudio/models/decoder/__init__.py +64 -0
- torchaudio/models/decoder/_ctc_decoder.py +568 -0
- torchaudio/models/decoder/_cuda_ctc_decoder.py +187 -0
- torchaudio/models/deepspeech.py +84 -0
- torchaudio/models/emformer.py +884 -0
- torchaudio/models/rnnt.py +816 -0
- torchaudio/models/rnnt_decoder.py +339 -0
- torchaudio/models/squim/__init__.py +11 -0
- torchaudio/models/squim/objective.py +326 -0
- torchaudio/models/squim/subjective.py +150 -0
- torchaudio/models/tacotron2.py +1046 -0
- torchaudio/models/wav2letter.py +72 -0
- torchaudio/models/wav2vec2/__init__.py +45 -0
- torchaudio/models/wav2vec2/components.py +1167 -0
- torchaudio/models/wav2vec2/model.py +1579 -0
- torchaudio/models/wav2vec2/utils/__init__.py +7 -0
- torchaudio/models/wav2vec2/utils/import_fairseq.py +213 -0
- torchaudio/models/wav2vec2/utils/import_huggingface.py +134 -0
- torchaudio/models/wav2vec2/wavlm_attention.py +214 -0
- torchaudio/models/wavernn.py +409 -0
- torchaudio/pipelines/__init__.py +102 -0
- torchaudio/pipelines/_source_separation_pipeline.py +109 -0
- torchaudio/pipelines/_squim_pipeline.py +156 -0
- torchaudio/pipelines/_tts/__init__.py +16 -0
- torchaudio/pipelines/_tts/impl.py +385 -0
- torchaudio/pipelines/_tts/interface.py +255 -0
- torchaudio/pipelines/_tts/utils.py +230 -0
- torchaudio/pipelines/_wav2vec2/__init__.py +0 -0
- torchaudio/pipelines/_wav2vec2/aligner.py +87 -0
- torchaudio/pipelines/_wav2vec2/impl.py +1699 -0
- torchaudio/pipelines/_wav2vec2/utils.py +346 -0
- torchaudio/pipelines/rnnt_pipeline.py +380 -0
- torchaudio/transforms/__init__.py +78 -0
- torchaudio/transforms/_multi_channel.py +467 -0
- torchaudio/transforms/_transforms.py +2138 -0
- torchaudio/utils/__init__.py +4 -0
- torchaudio/utils/download.py +89 -0
- torchaudio/version.py +2 -0
- torchaudio-2.9.0.dist-info/LICENSE +25 -0
- torchaudio-2.9.0.dist-info/METADATA +122 -0
- torchaudio-2.9.0.dist-info/RECORD +86 -0
- torchaudio-2.9.0.dist-info/WHEEL +5 -0
- torchaudio-2.9.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,1046 @@
|
|
|
1
|
+
# *****************************************************************************
|
|
2
|
+
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
|
|
3
|
+
#
|
|
4
|
+
# Redistribution and use in source and binary forms, with or without
|
|
5
|
+
# modification, are permitted provided that the following conditions are met:
|
|
6
|
+
# * Redistributions of source code must retain the above copyright
|
|
7
|
+
# notice, this list of conditions and the following disclaimer.
|
|
8
|
+
# * Redistributions in binary form must reproduce the above copyright
|
|
9
|
+
# notice, this list of conditions and the following disclaimer in the
|
|
10
|
+
# documentation and/or other materials provided with the distribution.
|
|
11
|
+
# * Neither the name of the NVIDIA CORPORATION nor the
|
|
12
|
+
# names of its contributors may be used to endorse or promote products
|
|
13
|
+
# derived from this software without specific prior written permission.
|
|
14
|
+
#
|
|
15
|
+
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
|
16
|
+
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
|
17
|
+
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
18
|
+
# DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY
|
|
19
|
+
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
|
20
|
+
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
|
21
|
+
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
|
22
|
+
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
|
23
|
+
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
|
24
|
+
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
25
|
+
#
|
|
26
|
+
# *****************************************************************************
|
|
27
|
+
|
|
28
|
+
import warnings
|
|
29
|
+
from typing import List, Optional, Tuple, Union
|
|
30
|
+
|
|
31
|
+
import torch
|
|
32
|
+
from torch import nn, Tensor
|
|
33
|
+
from torch.nn import functional as F
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
__all__ = [
|
|
37
|
+
"Tacotron2",
|
|
38
|
+
]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _get_linear_layer(in_dim: int, out_dim: int, bias: bool = True, w_init_gain: str = "linear") -> torch.nn.Linear:
|
|
42
|
+
r"""Linear layer with xavier uniform initialization.
|
|
43
|
+
|
|
44
|
+
Args:
|
|
45
|
+
in_dim (int): Size of each input sample.
|
|
46
|
+
out_dim (int): Size of each output sample.
|
|
47
|
+
bias (bool, optional): If set to ``False``, the layer will not learn an additive bias. (Default: ``True``)
|
|
48
|
+
w_init_gain (str, optional): Parameter passed to ``torch.nn.init.calculate_gain``
|
|
49
|
+
for setting the gain parameter of ``xavier_uniform_``. (Default: ``linear``)
|
|
50
|
+
|
|
51
|
+
Returns:
|
|
52
|
+
(torch.nn.Linear): The corresponding linear layer.
|
|
53
|
+
"""
|
|
54
|
+
linear = torch.nn.Linear(in_dim, out_dim, bias=bias)
|
|
55
|
+
torch.nn.init.xavier_uniform_(linear.weight, gain=torch.nn.init.calculate_gain(w_init_gain))
|
|
56
|
+
return linear
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _get_conv1d_layer(
|
|
60
|
+
in_channels: int,
|
|
61
|
+
out_channels: int,
|
|
62
|
+
kernel_size: int = 1,
|
|
63
|
+
stride: int = 1,
|
|
64
|
+
padding: Optional[Union[str, int, Tuple[int]]] = None,
|
|
65
|
+
dilation: int = 1,
|
|
66
|
+
bias: bool = True,
|
|
67
|
+
w_init_gain: str = "linear",
|
|
68
|
+
) -> torch.nn.Conv1d:
|
|
69
|
+
r"""1D convolution with xavier uniform initialization.
|
|
70
|
+
|
|
71
|
+
Args:
|
|
72
|
+
in_channels (int): Number of channels in the input image.
|
|
73
|
+
out_channels (int): Number of channels produced by the convolution.
|
|
74
|
+
kernel_size (int, optional): Number of channels in the input image. (Default: ``1``)
|
|
75
|
+
stride (int, optional): Number of channels in the input image. (Default: ``1``)
|
|
76
|
+
padding (str, int or tuple, optional): Padding added to both sides of the input.
|
|
77
|
+
(Default: dilation * (kernel_size - 1) / 2)
|
|
78
|
+
dilation (int, optional): Number of channels in the input image. (Default: ``1``)
|
|
79
|
+
w_init_gain (str, optional): Parameter passed to ``torch.nn.init.calculate_gain``
|
|
80
|
+
for setting the gain parameter of ``xavier_uniform_``. (Default: ``linear``)
|
|
81
|
+
|
|
82
|
+
Returns:
|
|
83
|
+
(torch.nn.Conv1d): The corresponding Conv1D layer.
|
|
84
|
+
"""
|
|
85
|
+
if padding is None:
|
|
86
|
+
if kernel_size % 2 != 1:
|
|
87
|
+
raise ValueError("kernel_size must be odd")
|
|
88
|
+
padding = int(dilation * (kernel_size - 1) / 2)
|
|
89
|
+
|
|
90
|
+
conv1d = torch.nn.Conv1d(
|
|
91
|
+
in_channels,
|
|
92
|
+
out_channels,
|
|
93
|
+
kernel_size=kernel_size,
|
|
94
|
+
stride=stride,
|
|
95
|
+
padding=padding,
|
|
96
|
+
dilation=dilation,
|
|
97
|
+
bias=bias,
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
torch.nn.init.xavier_uniform_(conv1d.weight, gain=torch.nn.init.calculate_gain(w_init_gain))
|
|
101
|
+
|
|
102
|
+
return conv1d
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _get_mask_from_lengths(lengths: Tensor) -> Tensor:
|
|
106
|
+
r"""Returns a binary mask based on ``lengths``. The ``i``-th row and ``j``-th column of the mask
|
|
107
|
+
is ``1`` if ``j`` is smaller than ``i``-th element of ``lengths.
|
|
108
|
+
|
|
109
|
+
Args:
|
|
110
|
+
lengths (Tensor): The length of each element in the batch, with shape (n_batch, ).
|
|
111
|
+
|
|
112
|
+
Returns:
|
|
113
|
+
mask (Tensor): The binary mask, with shape (n_batch, max of ``lengths``).
|
|
114
|
+
"""
|
|
115
|
+
max_len = torch.max(lengths).item()
|
|
116
|
+
ids = torch.arange(0, max_len, device=lengths.device, dtype=lengths.dtype)
|
|
117
|
+
mask = (ids < lengths.unsqueeze(1)).byte()
|
|
118
|
+
mask = torch.le(mask, 0)
|
|
119
|
+
return mask
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class _LocationLayer(nn.Module):
|
|
123
|
+
r"""Location layer used in the Attention model.
|
|
124
|
+
|
|
125
|
+
Args:
|
|
126
|
+
attention_n_filter (int): Number of filters for attention model.
|
|
127
|
+
attention_kernel_size (int): Kernel size for attention model.
|
|
128
|
+
attention_hidden_dim (int): Dimension of attention hidden representation.
|
|
129
|
+
"""
|
|
130
|
+
|
|
131
|
+
def __init__(
|
|
132
|
+
self,
|
|
133
|
+
attention_n_filter: int,
|
|
134
|
+
attention_kernel_size: int,
|
|
135
|
+
attention_hidden_dim: int,
|
|
136
|
+
):
|
|
137
|
+
super().__init__()
|
|
138
|
+
padding = int((attention_kernel_size - 1) / 2)
|
|
139
|
+
self.location_conv = _get_conv1d_layer(
|
|
140
|
+
2,
|
|
141
|
+
attention_n_filter,
|
|
142
|
+
kernel_size=attention_kernel_size,
|
|
143
|
+
padding=padding,
|
|
144
|
+
bias=False,
|
|
145
|
+
stride=1,
|
|
146
|
+
dilation=1,
|
|
147
|
+
)
|
|
148
|
+
self.location_dense = _get_linear_layer(
|
|
149
|
+
attention_n_filter, attention_hidden_dim, bias=False, w_init_gain="tanh"
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
def forward(self, attention_weights_cat: Tensor) -> Tensor:
|
|
153
|
+
r"""Location layer used in the Attention model.
|
|
154
|
+
|
|
155
|
+
Args:
|
|
156
|
+
attention_weights_cat (Tensor): Cumulative and previous attention weights
|
|
157
|
+
with shape (n_batch, 2, max of ``text_lengths``).
|
|
158
|
+
|
|
159
|
+
Returns:
|
|
160
|
+
processed_attention (Tensor): Cumulative and previous attention weights
|
|
161
|
+
with shape (n_batch, ``attention_hidden_dim``).
|
|
162
|
+
"""
|
|
163
|
+
# (n_batch, attention_n_filter, text_lengths.max())
|
|
164
|
+
processed_attention = self.location_conv(attention_weights_cat)
|
|
165
|
+
processed_attention = processed_attention.transpose(1, 2)
|
|
166
|
+
# (n_batch, text_lengths.max(), attention_hidden_dim)
|
|
167
|
+
processed_attention = self.location_dense(processed_attention)
|
|
168
|
+
return processed_attention
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
class _Attention(nn.Module):
|
|
172
|
+
r"""Locally sensitive attention model.
|
|
173
|
+
|
|
174
|
+
Args:
|
|
175
|
+
attention_rnn_dim (int): Number of hidden units for RNN.
|
|
176
|
+
encoder_embedding_dim (int): Number of embedding dimensions in the Encoder.
|
|
177
|
+
attention_hidden_dim (int): Dimension of attention hidden representation.
|
|
178
|
+
attention_location_n_filter (int): Number of filters for Attention model.
|
|
179
|
+
attention_location_kernel_size (int): Kernel size for Attention model.
|
|
180
|
+
"""
|
|
181
|
+
|
|
182
|
+
def __init__(
|
|
183
|
+
self,
|
|
184
|
+
attention_rnn_dim: int,
|
|
185
|
+
encoder_embedding_dim: int,
|
|
186
|
+
attention_hidden_dim: int,
|
|
187
|
+
attention_location_n_filter: int,
|
|
188
|
+
attention_location_kernel_size: int,
|
|
189
|
+
) -> None:
|
|
190
|
+
super().__init__()
|
|
191
|
+
self.query_layer = _get_linear_layer(attention_rnn_dim, attention_hidden_dim, bias=False, w_init_gain="tanh")
|
|
192
|
+
self.memory_layer = _get_linear_layer(
|
|
193
|
+
encoder_embedding_dim, attention_hidden_dim, bias=False, w_init_gain="tanh"
|
|
194
|
+
)
|
|
195
|
+
self.v = _get_linear_layer(attention_hidden_dim, 1, bias=False)
|
|
196
|
+
self.location_layer = _LocationLayer(
|
|
197
|
+
attention_location_n_filter,
|
|
198
|
+
attention_location_kernel_size,
|
|
199
|
+
attention_hidden_dim,
|
|
200
|
+
)
|
|
201
|
+
self.score_mask_value = -float("inf")
|
|
202
|
+
|
|
203
|
+
def _get_alignment_energies(self, query: Tensor, processed_memory: Tensor, attention_weights_cat: Tensor) -> Tensor:
|
|
204
|
+
r"""Get the alignment vector.
|
|
205
|
+
|
|
206
|
+
Args:
|
|
207
|
+
query (Tensor): Decoder output with shape (n_batch, n_mels * n_frames_per_step).
|
|
208
|
+
processed_memory (Tensor): Processed Encoder outputs
|
|
209
|
+
with shape (n_batch, max of ``text_lengths``, attention_hidden_dim).
|
|
210
|
+
attention_weights_cat (Tensor): Cumulative and previous attention weights
|
|
211
|
+
with shape (n_batch, 2, max of ``text_lengths``).
|
|
212
|
+
|
|
213
|
+
Returns:
|
|
214
|
+
alignment (Tensor): attention weights, it is a tensor with shape (batch, max of ``text_lengths``).
|
|
215
|
+
"""
|
|
216
|
+
|
|
217
|
+
processed_query = self.query_layer(query.unsqueeze(1))
|
|
218
|
+
processed_attention_weights = self.location_layer(attention_weights_cat)
|
|
219
|
+
energies = self.v(torch.tanh(processed_query + processed_attention_weights + processed_memory))
|
|
220
|
+
|
|
221
|
+
alignment = energies.squeeze(2)
|
|
222
|
+
return alignment
|
|
223
|
+
|
|
224
|
+
def forward(
|
|
225
|
+
self,
|
|
226
|
+
attention_hidden_state: Tensor,
|
|
227
|
+
memory: Tensor,
|
|
228
|
+
processed_memory: Tensor,
|
|
229
|
+
attention_weights_cat: Tensor,
|
|
230
|
+
mask: Tensor,
|
|
231
|
+
) -> Tuple[Tensor, Tensor]:
|
|
232
|
+
r"""Pass the input through the Attention model.
|
|
233
|
+
|
|
234
|
+
Args:
|
|
235
|
+
attention_hidden_state (Tensor): Attention rnn last output with shape (n_batch, ``attention_rnn_dim``).
|
|
236
|
+
memory (Tensor): Encoder outputs with shape (n_batch, max of ``text_lengths``, ``encoder_embedding_dim``).
|
|
237
|
+
processed_memory (Tensor): Processed Encoder outputs
|
|
238
|
+
with shape (n_batch, max of ``text_lengths``, ``attention_hidden_dim``).
|
|
239
|
+
attention_weights_cat (Tensor): Previous and cumulative attention weights
|
|
240
|
+
with shape (n_batch, current_num_frames * 2, max of ``text_lengths``).
|
|
241
|
+
mask (Tensor): Binary mask for padded data with shape (n_batch, current_num_frames).
|
|
242
|
+
|
|
243
|
+
Returns:
|
|
244
|
+
attention_context (Tensor): Context vector with shape (n_batch, ``encoder_embedding_dim``).
|
|
245
|
+
attention_weights (Tensor): Attention weights with shape (n_batch, max of ``text_lengths``).
|
|
246
|
+
"""
|
|
247
|
+
alignment = self._get_alignment_energies(attention_hidden_state, processed_memory, attention_weights_cat)
|
|
248
|
+
|
|
249
|
+
alignment = alignment.masked_fill(mask, self.score_mask_value)
|
|
250
|
+
|
|
251
|
+
attention_weights = F.softmax(alignment, dim=1)
|
|
252
|
+
attention_context = torch.bmm(attention_weights.unsqueeze(1), memory)
|
|
253
|
+
attention_context = attention_context.squeeze(1)
|
|
254
|
+
|
|
255
|
+
return attention_context, attention_weights
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
class _Prenet(nn.Module):
|
|
259
|
+
r"""Prenet Module. It is consists of ``len(output_size)`` linear layers.
|
|
260
|
+
|
|
261
|
+
Args:
|
|
262
|
+
in_dim (int): The size of each input sample.
|
|
263
|
+
output_sizes (list): The output dimension of each linear layers.
|
|
264
|
+
"""
|
|
265
|
+
|
|
266
|
+
def __init__(self, in_dim: int, out_sizes: List[int]) -> None:
|
|
267
|
+
super().__init__()
|
|
268
|
+
in_sizes = [in_dim] + out_sizes[:-1]
|
|
269
|
+
self.layers = nn.ModuleList(
|
|
270
|
+
[_get_linear_layer(in_size, out_size, bias=False) for (in_size, out_size) in zip(in_sizes, out_sizes)]
|
|
271
|
+
)
|
|
272
|
+
|
|
273
|
+
def forward(self, x: Tensor) -> Tensor:
|
|
274
|
+
r"""Pass the input through Prenet.
|
|
275
|
+
|
|
276
|
+
Args:
|
|
277
|
+
x (Tensor): The input sequence to Prenet with shape (n_batch, in_dim).
|
|
278
|
+
|
|
279
|
+
Return:
|
|
280
|
+
x (Tensor): Tensor with shape (n_batch, sizes[-1])
|
|
281
|
+
"""
|
|
282
|
+
|
|
283
|
+
for linear in self.layers:
|
|
284
|
+
x = F.dropout(F.relu(linear(x)), p=0.5, training=True)
|
|
285
|
+
return x
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
class _Postnet(nn.Module):
|
|
289
|
+
r"""Postnet Module.
|
|
290
|
+
|
|
291
|
+
Args:
|
|
292
|
+
n_mels (int): Number of mel bins.
|
|
293
|
+
postnet_embedding_dim (int): Postnet embedding dimension.
|
|
294
|
+
postnet_kernel_size (int): Postnet kernel size.
|
|
295
|
+
postnet_n_convolution (int): Number of postnet convolutions.
|
|
296
|
+
"""
|
|
297
|
+
|
|
298
|
+
def __init__(
|
|
299
|
+
self,
|
|
300
|
+
n_mels: int,
|
|
301
|
+
postnet_embedding_dim: int,
|
|
302
|
+
postnet_kernel_size: int,
|
|
303
|
+
postnet_n_convolution: int,
|
|
304
|
+
):
|
|
305
|
+
super().__init__()
|
|
306
|
+
self.convolutions = nn.ModuleList()
|
|
307
|
+
|
|
308
|
+
for i in range(postnet_n_convolution):
|
|
309
|
+
in_channels = n_mels if i == 0 else postnet_embedding_dim
|
|
310
|
+
out_channels = n_mels if i == (postnet_n_convolution - 1) else postnet_embedding_dim
|
|
311
|
+
init_gain = "linear" if i == (postnet_n_convolution - 1) else "tanh"
|
|
312
|
+
num_features = n_mels if i == (postnet_n_convolution - 1) else postnet_embedding_dim
|
|
313
|
+
self.convolutions.append(
|
|
314
|
+
nn.Sequential(
|
|
315
|
+
_get_conv1d_layer(
|
|
316
|
+
in_channels,
|
|
317
|
+
out_channels,
|
|
318
|
+
kernel_size=postnet_kernel_size,
|
|
319
|
+
stride=1,
|
|
320
|
+
padding=int((postnet_kernel_size - 1) / 2),
|
|
321
|
+
dilation=1,
|
|
322
|
+
w_init_gain=init_gain,
|
|
323
|
+
),
|
|
324
|
+
nn.BatchNorm1d(num_features),
|
|
325
|
+
)
|
|
326
|
+
)
|
|
327
|
+
|
|
328
|
+
self.n_convs = len(self.convolutions)
|
|
329
|
+
|
|
330
|
+
def forward(self, x: Tensor) -> Tensor:
|
|
331
|
+
r"""Pass the input through Postnet.
|
|
332
|
+
|
|
333
|
+
Args:
|
|
334
|
+
x (Tensor): The input sequence with shape (n_batch, ``n_mels``, max of ``mel_specgram_lengths``).
|
|
335
|
+
|
|
336
|
+
Return:
|
|
337
|
+
x (Tensor): Tensor with shape (n_batch, ``n_mels``, max of ``mel_specgram_lengths``).
|
|
338
|
+
"""
|
|
339
|
+
|
|
340
|
+
for i, conv in enumerate(self.convolutions):
|
|
341
|
+
if i < self.n_convs - 1:
|
|
342
|
+
x = F.dropout(torch.tanh(conv(x)), 0.5, training=self.training)
|
|
343
|
+
else:
|
|
344
|
+
x = F.dropout(conv(x), 0.5, training=self.training)
|
|
345
|
+
|
|
346
|
+
return x
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
class _Encoder(nn.Module):
|
|
350
|
+
r"""Encoder Module.
|
|
351
|
+
|
|
352
|
+
Args:
|
|
353
|
+
encoder_embedding_dim (int): Number of embedding dimensions in the encoder.
|
|
354
|
+
encoder_n_convolution (int): Number of convolution layers in the encoder.
|
|
355
|
+
encoder_kernel_size (int): The kernel size in the encoder.
|
|
356
|
+
|
|
357
|
+
Examples
|
|
358
|
+
>>> encoder = _Encoder(3, 512, 5)
|
|
359
|
+
>>> input = torch.rand(10, 20, 30)
|
|
360
|
+
>>> output = encoder(input) # shape: (10, 30, 512)
|
|
361
|
+
"""
|
|
362
|
+
|
|
363
|
+
def __init__(
|
|
364
|
+
self,
|
|
365
|
+
encoder_embedding_dim: int,
|
|
366
|
+
encoder_n_convolution: int,
|
|
367
|
+
encoder_kernel_size: int,
|
|
368
|
+
) -> None:
|
|
369
|
+
super().__init__()
|
|
370
|
+
|
|
371
|
+
self.convolutions = nn.ModuleList()
|
|
372
|
+
for _ in range(encoder_n_convolution):
|
|
373
|
+
conv_layer = nn.Sequential(
|
|
374
|
+
_get_conv1d_layer(
|
|
375
|
+
encoder_embedding_dim,
|
|
376
|
+
encoder_embedding_dim,
|
|
377
|
+
kernel_size=encoder_kernel_size,
|
|
378
|
+
stride=1,
|
|
379
|
+
padding=int((encoder_kernel_size - 1) / 2),
|
|
380
|
+
dilation=1,
|
|
381
|
+
w_init_gain="relu",
|
|
382
|
+
),
|
|
383
|
+
nn.BatchNorm1d(encoder_embedding_dim),
|
|
384
|
+
)
|
|
385
|
+
self.convolutions.append(conv_layer)
|
|
386
|
+
|
|
387
|
+
self.lstm = nn.LSTM(
|
|
388
|
+
encoder_embedding_dim,
|
|
389
|
+
int(encoder_embedding_dim / 2),
|
|
390
|
+
1,
|
|
391
|
+
batch_first=True,
|
|
392
|
+
bidirectional=True,
|
|
393
|
+
)
|
|
394
|
+
self.lstm.flatten_parameters()
|
|
395
|
+
|
|
396
|
+
def forward(self, x: Tensor, input_lengths: Tensor) -> Tensor:
|
|
397
|
+
r"""Pass the input through the Encoder.
|
|
398
|
+
|
|
399
|
+
Args:
|
|
400
|
+
x (Tensor): The input sequences with shape (n_batch, encoder_embedding_dim, n_seq).
|
|
401
|
+
input_lengths (Tensor): The length of each input sequence with shape (n_batch, ).
|
|
402
|
+
|
|
403
|
+
Return:
|
|
404
|
+
x (Tensor): A tensor with shape (n_batch, n_seq, encoder_embedding_dim).
|
|
405
|
+
"""
|
|
406
|
+
|
|
407
|
+
for conv in self.convolutions:
|
|
408
|
+
x = F.dropout(F.relu(conv(x)), 0.5, self.training)
|
|
409
|
+
|
|
410
|
+
x = x.transpose(1, 2)
|
|
411
|
+
|
|
412
|
+
input_lengths = input_lengths.cpu()
|
|
413
|
+
x = nn.utils.rnn.pack_padded_sequence(x, input_lengths, batch_first=True)
|
|
414
|
+
|
|
415
|
+
outputs, _ = self.lstm(x)
|
|
416
|
+
outputs, _ = nn.utils.rnn.pad_packed_sequence(outputs, batch_first=True)
|
|
417
|
+
|
|
418
|
+
return outputs
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
class _Decoder(nn.Module):
|
|
422
|
+
r"""Decoder with Attention model.
|
|
423
|
+
|
|
424
|
+
Args:
|
|
425
|
+
n_mels (int): number of mel bins
|
|
426
|
+
n_frames_per_step (int): number of frames processed per step, only 1 is supported
|
|
427
|
+
encoder_embedding_dim (int): the number of embedding dimensions in the encoder.
|
|
428
|
+
decoder_rnn_dim (int): number of units in decoder LSTM
|
|
429
|
+
decoder_max_step (int): maximum number of output mel spectrograms
|
|
430
|
+
decoder_dropout (float): dropout probability for decoder LSTM
|
|
431
|
+
decoder_early_stopping (bool): stop decoding when all samples are finished
|
|
432
|
+
attention_rnn_dim (int): number of units in attention LSTM
|
|
433
|
+
attention_hidden_dim (int): dimension of attention hidden representation
|
|
434
|
+
attention_location_n_filter (int): number of filters for attention model
|
|
435
|
+
attention_location_kernel_size (int): kernel size for attention model
|
|
436
|
+
attention_dropout (float): dropout probability for attention LSTM
|
|
437
|
+
prenet_dim (int): number of ReLU units in prenet layers
|
|
438
|
+
gate_threshold (float): probability threshold for stop token
|
|
439
|
+
"""
|
|
440
|
+
|
|
441
|
+
def __init__(
|
|
442
|
+
self,
|
|
443
|
+
n_mels: int,
|
|
444
|
+
n_frames_per_step: int,
|
|
445
|
+
encoder_embedding_dim: int,
|
|
446
|
+
decoder_rnn_dim: int,
|
|
447
|
+
decoder_max_step: int,
|
|
448
|
+
decoder_dropout: float,
|
|
449
|
+
decoder_early_stopping: bool,
|
|
450
|
+
attention_rnn_dim: int,
|
|
451
|
+
attention_hidden_dim: int,
|
|
452
|
+
attention_location_n_filter: int,
|
|
453
|
+
attention_location_kernel_size: int,
|
|
454
|
+
attention_dropout: float,
|
|
455
|
+
prenet_dim: int,
|
|
456
|
+
gate_threshold: float,
|
|
457
|
+
) -> None:
|
|
458
|
+
|
|
459
|
+
super().__init__()
|
|
460
|
+
self.n_mels = n_mels
|
|
461
|
+
self.n_frames_per_step = n_frames_per_step
|
|
462
|
+
self.encoder_embedding_dim = encoder_embedding_dim
|
|
463
|
+
self.attention_rnn_dim = attention_rnn_dim
|
|
464
|
+
self.decoder_rnn_dim = decoder_rnn_dim
|
|
465
|
+
self.prenet_dim = prenet_dim
|
|
466
|
+
self.decoder_max_step = decoder_max_step
|
|
467
|
+
self.gate_threshold = gate_threshold
|
|
468
|
+
self.attention_dropout = attention_dropout
|
|
469
|
+
self.decoder_dropout = decoder_dropout
|
|
470
|
+
self.decoder_early_stopping = decoder_early_stopping
|
|
471
|
+
|
|
472
|
+
self.prenet = _Prenet(n_mels * n_frames_per_step, [prenet_dim, prenet_dim])
|
|
473
|
+
|
|
474
|
+
self.attention_rnn = nn.LSTMCell(prenet_dim + encoder_embedding_dim, attention_rnn_dim)
|
|
475
|
+
|
|
476
|
+
self.attention_layer = _Attention(
|
|
477
|
+
attention_rnn_dim,
|
|
478
|
+
encoder_embedding_dim,
|
|
479
|
+
attention_hidden_dim,
|
|
480
|
+
attention_location_n_filter,
|
|
481
|
+
attention_location_kernel_size,
|
|
482
|
+
)
|
|
483
|
+
|
|
484
|
+
self.decoder_rnn = nn.LSTMCell(attention_rnn_dim + encoder_embedding_dim, decoder_rnn_dim, True)
|
|
485
|
+
|
|
486
|
+
self.linear_projection = _get_linear_layer(decoder_rnn_dim + encoder_embedding_dim, n_mels * n_frames_per_step)
|
|
487
|
+
|
|
488
|
+
self.gate_layer = _get_linear_layer(
|
|
489
|
+
decoder_rnn_dim + encoder_embedding_dim, 1, bias=True, w_init_gain="sigmoid"
|
|
490
|
+
)
|
|
491
|
+
|
|
492
|
+
def _get_initial_frame(self, memory: Tensor) -> Tensor:
|
|
493
|
+
r"""Gets all zeros frames to use as the first decoder input.
|
|
494
|
+
|
|
495
|
+
Args:
|
|
496
|
+
memory (Tensor): Encoder outputs with shape (n_batch, max of ``text_lengths``, ``encoder_embedding_dim``).
|
|
497
|
+
|
|
498
|
+
Returns:
|
|
499
|
+
decoder_input (Tensor): all zeros frames with shape
|
|
500
|
+
(n_batch, max of ``text_lengths``, ``n_mels * n_frames_per_step``).
|
|
501
|
+
"""
|
|
502
|
+
|
|
503
|
+
n_batch = memory.size(0)
|
|
504
|
+
dtype = memory.dtype
|
|
505
|
+
device = memory.device
|
|
506
|
+
decoder_input = torch.zeros(n_batch, self.n_mels * self.n_frames_per_step, dtype=dtype, device=device)
|
|
507
|
+
return decoder_input
|
|
508
|
+
|
|
509
|
+
def _initialize_decoder_states(
|
|
510
|
+
self, memory: Tensor
|
|
511
|
+
) -> Tuple[Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor]:
|
|
512
|
+
r"""Initializes attention rnn states, decoder rnn states, attention
|
|
513
|
+
weights, attention cumulative weights, attention context, stores memory
|
|
514
|
+
and stores processed memory.
|
|
515
|
+
|
|
516
|
+
Args:
|
|
517
|
+
memory (Tensor): Encoder outputs with shape (n_batch, max of ``text_lengths``, ``encoder_embedding_dim``).
|
|
518
|
+
|
|
519
|
+
Returns:
|
|
520
|
+
attention_hidden (Tensor): Hidden state of the attention LSTM with shape (n_batch, ``attention_rnn_dim``).
|
|
521
|
+
attention_cell (Tensor): Hidden state of the attention LSTM with shape (n_batch, ``attention_rnn_dim``).
|
|
522
|
+
decoder_hidden (Tensor): Hidden state of the decoder LSTM with shape (n_batch, ``decoder_rnn_dim``).
|
|
523
|
+
decoder_cell (Tensor): Hidden state of the decoder LSTM with shape (n_batch, ``decoder_rnn_dim``).
|
|
524
|
+
attention_weights (Tensor): Attention weights with shape (n_batch, max of ``text_lengths``).
|
|
525
|
+
attention_weights_cum (Tensor): Cumulated attention weights with shape (n_batch, max of ``text_lengths``).
|
|
526
|
+
attention_context (Tensor): Context vector with shape (n_batch, ``encoder_embedding_dim``).
|
|
527
|
+
processed_memory (Tensor): Processed encoder outputs
|
|
528
|
+
with shape (n_batch, max of ``text_lengths``, ``attention_hidden_dim``).
|
|
529
|
+
"""
|
|
530
|
+
n_batch = memory.size(0)
|
|
531
|
+
max_time = memory.size(1)
|
|
532
|
+
dtype = memory.dtype
|
|
533
|
+
device = memory.device
|
|
534
|
+
|
|
535
|
+
attention_hidden = torch.zeros(n_batch, self.attention_rnn_dim, dtype=dtype, device=device)
|
|
536
|
+
attention_cell = torch.zeros(n_batch, self.attention_rnn_dim, dtype=dtype, device=device)
|
|
537
|
+
|
|
538
|
+
decoder_hidden = torch.zeros(n_batch, self.decoder_rnn_dim, dtype=dtype, device=device)
|
|
539
|
+
decoder_cell = torch.zeros(n_batch, self.decoder_rnn_dim, dtype=dtype, device=device)
|
|
540
|
+
|
|
541
|
+
attention_weights = torch.zeros(n_batch, max_time, dtype=dtype, device=device)
|
|
542
|
+
attention_weights_cum = torch.zeros(n_batch, max_time, dtype=dtype, device=device)
|
|
543
|
+
attention_context = torch.zeros(n_batch, self.encoder_embedding_dim, dtype=dtype, device=device)
|
|
544
|
+
|
|
545
|
+
processed_memory = self.attention_layer.memory_layer(memory)
|
|
546
|
+
|
|
547
|
+
return (
|
|
548
|
+
attention_hidden,
|
|
549
|
+
attention_cell,
|
|
550
|
+
decoder_hidden,
|
|
551
|
+
decoder_cell,
|
|
552
|
+
attention_weights,
|
|
553
|
+
attention_weights_cum,
|
|
554
|
+
attention_context,
|
|
555
|
+
processed_memory,
|
|
556
|
+
)
|
|
557
|
+
|
|
558
|
+
def _parse_decoder_inputs(self, decoder_inputs: Tensor) -> Tensor:
|
|
559
|
+
r"""Prepares decoder inputs.
|
|
560
|
+
|
|
561
|
+
Args:
|
|
562
|
+
decoder_inputs (Tensor): Inputs used for teacher-forced training, i.e. mel-specs,
|
|
563
|
+
with shape (n_batch, ``n_mels``, max of ``mel_specgram_lengths``)
|
|
564
|
+
|
|
565
|
+
Returns:
|
|
566
|
+
inputs (Tensor): Processed decoder inputs with shape (max of ``mel_specgram_lengths``, n_batch, ``n_mels``).
|
|
567
|
+
"""
|
|
568
|
+
# (n_batch, n_mels, mel_specgram_lengths.max()) -> (n_batch, mel_specgram_lengths.max(), n_mels)
|
|
569
|
+
decoder_inputs = decoder_inputs.transpose(1, 2)
|
|
570
|
+
decoder_inputs = decoder_inputs.view(
|
|
571
|
+
decoder_inputs.size(0),
|
|
572
|
+
int(decoder_inputs.size(1) / self.n_frames_per_step),
|
|
573
|
+
-1,
|
|
574
|
+
)
|
|
575
|
+
# (n_batch, mel_specgram_lengths.max(), n_mels) -> (mel_specgram_lengths.max(), n_batch, n_mels)
|
|
576
|
+
decoder_inputs = decoder_inputs.transpose(0, 1)
|
|
577
|
+
return decoder_inputs
|
|
578
|
+
|
|
579
|
+
def _parse_decoder_outputs(
|
|
580
|
+
self, mel_specgram: Tensor, gate_outputs: Tensor, alignments: Tensor
|
|
581
|
+
) -> Tuple[Tensor, Tensor, Tensor]:
|
|
582
|
+
r"""Prepares decoder outputs for output
|
|
583
|
+
|
|
584
|
+
Args:
|
|
585
|
+
mel_specgram (Tensor): mel spectrogram with shape (max of ``mel_specgram_lengths``, n_batch, ``n_mels``)
|
|
586
|
+
gate_outputs (Tensor): predicted stop token with shape (max of ``mel_specgram_lengths``, n_batch)
|
|
587
|
+
alignments (Tensor): sequence of attention weights from the decoder
|
|
588
|
+
with shape (max of ``mel_specgram_lengths``, n_batch, max of ``text_lengths``)
|
|
589
|
+
|
|
590
|
+
Returns:
|
|
591
|
+
mel_specgram (Tensor): mel spectrogram with shape (n_batch, ``n_mels``, max of ``mel_specgram_lengths``)
|
|
592
|
+
gate_outputs (Tensor): predicted stop token with shape (n_batch, max of ``mel_specgram_lengths``)
|
|
593
|
+
alignments (Tensor): sequence of attention weights from the decoder
|
|
594
|
+
with shape (n_batch, max of ``mel_specgram_lengths``, max of ``text_lengths``)
|
|
595
|
+
"""
|
|
596
|
+
# (mel_specgram_lengths.max(), n_batch, text_lengths.max())
|
|
597
|
+
# -> (n_batch, mel_specgram_lengths.max(), text_lengths.max())
|
|
598
|
+
alignments = alignments.transpose(0, 1).contiguous()
|
|
599
|
+
# (mel_specgram_lengths.max(), n_batch) -> (n_batch, mel_specgram_lengths.max())
|
|
600
|
+
gate_outputs = gate_outputs.transpose(0, 1).contiguous()
|
|
601
|
+
# (mel_specgram_lengths.max(), n_batch, n_mels) -> (n_batch, mel_specgram_lengths.max(), n_mels)
|
|
602
|
+
mel_specgram = mel_specgram.transpose(0, 1).contiguous()
|
|
603
|
+
# decouple frames per step
|
|
604
|
+
shape = (mel_specgram.shape[0], -1, self.n_mels)
|
|
605
|
+
mel_specgram = mel_specgram.view(*shape)
|
|
606
|
+
# (n_batch, mel_specgram_lengths.max(), n_mels) -> (n_batch, n_mels, T_out)
|
|
607
|
+
mel_specgram = mel_specgram.transpose(1, 2)
|
|
608
|
+
|
|
609
|
+
return mel_specgram, gate_outputs, alignments
|
|
610
|
+
|
|
611
|
+
def decode(
|
|
612
|
+
self,
|
|
613
|
+
decoder_input: Tensor,
|
|
614
|
+
attention_hidden: Tensor,
|
|
615
|
+
attention_cell: Tensor,
|
|
616
|
+
decoder_hidden: Tensor,
|
|
617
|
+
decoder_cell: Tensor,
|
|
618
|
+
attention_weights: Tensor,
|
|
619
|
+
attention_weights_cum: Tensor,
|
|
620
|
+
attention_context: Tensor,
|
|
621
|
+
memory: Tensor,
|
|
622
|
+
processed_memory: Tensor,
|
|
623
|
+
mask: Tensor,
|
|
624
|
+
) -> Tuple[Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor]:
|
|
625
|
+
r"""Decoder step using stored states, attention and memory
|
|
626
|
+
|
|
627
|
+
Args:
|
|
628
|
+
decoder_input (Tensor): Output of the Prenet with shape (n_batch, ``prenet_dim``).
|
|
629
|
+
attention_hidden (Tensor): Hidden state of the attention LSTM with shape (n_batch, ``attention_rnn_dim``).
|
|
630
|
+
attention_cell (Tensor): Hidden state of the attention LSTM with shape (n_batch, ``attention_rnn_dim``).
|
|
631
|
+
decoder_hidden (Tensor): Hidden state of the decoder LSTM with shape (n_batch, ``decoder_rnn_dim``).
|
|
632
|
+
decoder_cell (Tensor): Hidden state of the decoder LSTM with shape (n_batch, ``decoder_rnn_dim``).
|
|
633
|
+
attention_weights (Tensor): Attention weights with shape (n_batch, max of ``text_lengths``).
|
|
634
|
+
attention_weights_cum (Tensor): Cumulated attention weights with shape (n_batch, max of ``text_lengths``).
|
|
635
|
+
attention_context (Tensor): Context vector with shape (n_batch, ``encoder_embedding_dim``).
|
|
636
|
+
memory (Tensor): Encoder output with shape (n_batch, max of ``text_lengths``, ``encoder_embedding_dim``).
|
|
637
|
+
processed_memory (Tensor): Processed Encoder outputs
|
|
638
|
+
with shape (n_batch, max of ``text_lengths``, ``attention_hidden_dim``).
|
|
639
|
+
mask (Tensor): Binary mask for padded data with shape (n_batch, current_num_frames).
|
|
640
|
+
|
|
641
|
+
Returns:
|
|
642
|
+
decoder_output: Predicted mel spectrogram for the current frame with shape (n_batch, ``n_mels``).
|
|
643
|
+
gate_prediction (Tensor): Prediction of the stop token with shape (n_batch, ``1``).
|
|
644
|
+
attention_hidden (Tensor): Hidden state of the attention LSTM with shape (n_batch, ``attention_rnn_dim``).
|
|
645
|
+
attention_cell (Tensor): Hidden state of the attention LSTM with shape (n_batch, ``attention_rnn_dim``).
|
|
646
|
+
decoder_hidden (Tensor): Hidden state of the decoder LSTM with shape (n_batch, ``decoder_rnn_dim``).
|
|
647
|
+
decoder_cell (Tensor): Hidden state of the decoder LSTM with shape (n_batch, ``decoder_rnn_dim``).
|
|
648
|
+
attention_weights (Tensor): Attention weights with shape (n_batch, max of ``text_lengths``).
|
|
649
|
+
attention_weights_cum (Tensor): Cumulated attention weights with shape (n_batch, max of ``text_lengths``).
|
|
650
|
+
attention_context (Tensor): Context vector with shape (n_batch, ``encoder_embedding_dim``).
|
|
651
|
+
"""
|
|
652
|
+
cell_input = torch.cat((decoder_input, attention_context), -1)
|
|
653
|
+
|
|
654
|
+
attention_hidden, attention_cell = self.attention_rnn(cell_input, (attention_hidden, attention_cell))
|
|
655
|
+
attention_hidden = F.dropout(attention_hidden, self.attention_dropout, self.training)
|
|
656
|
+
|
|
657
|
+
attention_weights_cat = torch.cat((attention_weights.unsqueeze(1), attention_weights_cum.unsqueeze(1)), dim=1)
|
|
658
|
+
attention_context, attention_weights = self.attention_layer(
|
|
659
|
+
attention_hidden, memory, processed_memory, attention_weights_cat, mask
|
|
660
|
+
)
|
|
661
|
+
|
|
662
|
+
attention_weights_cum += attention_weights
|
|
663
|
+
decoder_input = torch.cat((attention_hidden, attention_context), -1)
|
|
664
|
+
|
|
665
|
+
decoder_hidden, decoder_cell = self.decoder_rnn(decoder_input, (decoder_hidden, decoder_cell))
|
|
666
|
+
decoder_hidden = F.dropout(decoder_hidden, self.decoder_dropout, self.training)
|
|
667
|
+
|
|
668
|
+
decoder_hidden_attention_context = torch.cat((decoder_hidden, attention_context), dim=1)
|
|
669
|
+
decoder_output = self.linear_projection(decoder_hidden_attention_context)
|
|
670
|
+
|
|
671
|
+
gate_prediction = self.gate_layer(decoder_hidden_attention_context)
|
|
672
|
+
|
|
673
|
+
return (
|
|
674
|
+
decoder_output,
|
|
675
|
+
gate_prediction,
|
|
676
|
+
attention_hidden,
|
|
677
|
+
attention_cell,
|
|
678
|
+
decoder_hidden,
|
|
679
|
+
decoder_cell,
|
|
680
|
+
attention_weights,
|
|
681
|
+
attention_weights_cum,
|
|
682
|
+
attention_context,
|
|
683
|
+
)
|
|
684
|
+
|
|
685
|
+
def forward(
|
|
686
|
+
self, memory: Tensor, mel_specgram_truth: Tensor, memory_lengths: Tensor
|
|
687
|
+
) -> Tuple[Tensor, Tensor, Tensor]:
|
|
688
|
+
r"""Decoder forward pass for training.
|
|
689
|
+
|
|
690
|
+
Args:
|
|
691
|
+
memory (Tensor): Encoder outputs
|
|
692
|
+
with shape (n_batch, max of ``text_lengths``, ``encoder_embedding_dim``).
|
|
693
|
+
mel_specgram_truth (Tensor): Decoder ground-truth mel-specs for teacher forcing
|
|
694
|
+
with shape (n_batch, ``n_mels``, max of ``mel_specgram_lengths``).
|
|
695
|
+
memory_lengths (Tensor): Encoder output lengths for attention masking
|
|
696
|
+
(the same as ``text_lengths``) with shape (n_batch, ).
|
|
697
|
+
|
|
698
|
+
Returns:
|
|
699
|
+
mel_specgram (Tensor): Predicted mel spectrogram
|
|
700
|
+
with shape (n_batch, ``n_mels``, max of ``mel_specgram_lengths``).
|
|
701
|
+
gate_outputs (Tensor): Predicted stop token for each timestep
|
|
702
|
+
with shape (n_batch, max of ``mel_specgram_lengths``).
|
|
703
|
+
alignments (Tensor): Sequence of attention weights from the decoder
|
|
704
|
+
with shape (n_batch, max of ``mel_specgram_lengths``, max of ``text_lengths``).
|
|
705
|
+
"""
|
|
706
|
+
|
|
707
|
+
decoder_input = self._get_initial_frame(memory).unsqueeze(0)
|
|
708
|
+
decoder_inputs = self._parse_decoder_inputs(mel_specgram_truth)
|
|
709
|
+
decoder_inputs = torch.cat((decoder_input, decoder_inputs), dim=0)
|
|
710
|
+
decoder_inputs = self.prenet(decoder_inputs)
|
|
711
|
+
|
|
712
|
+
mask = _get_mask_from_lengths(memory_lengths)
|
|
713
|
+
(
|
|
714
|
+
attention_hidden,
|
|
715
|
+
attention_cell,
|
|
716
|
+
decoder_hidden,
|
|
717
|
+
decoder_cell,
|
|
718
|
+
attention_weights,
|
|
719
|
+
attention_weights_cum,
|
|
720
|
+
attention_context,
|
|
721
|
+
processed_memory,
|
|
722
|
+
) = self._initialize_decoder_states(memory)
|
|
723
|
+
|
|
724
|
+
mel_outputs, gate_outputs, alignments = [], [], []
|
|
725
|
+
while len(mel_outputs) < decoder_inputs.size(0) - 1:
|
|
726
|
+
decoder_input = decoder_inputs[len(mel_outputs)]
|
|
727
|
+
(
|
|
728
|
+
mel_output,
|
|
729
|
+
gate_output,
|
|
730
|
+
attention_hidden,
|
|
731
|
+
attention_cell,
|
|
732
|
+
decoder_hidden,
|
|
733
|
+
decoder_cell,
|
|
734
|
+
attention_weights,
|
|
735
|
+
attention_weights_cum,
|
|
736
|
+
attention_context,
|
|
737
|
+
) = self.decode(
|
|
738
|
+
decoder_input,
|
|
739
|
+
attention_hidden,
|
|
740
|
+
attention_cell,
|
|
741
|
+
decoder_hidden,
|
|
742
|
+
decoder_cell,
|
|
743
|
+
attention_weights,
|
|
744
|
+
attention_weights_cum,
|
|
745
|
+
attention_context,
|
|
746
|
+
memory,
|
|
747
|
+
processed_memory,
|
|
748
|
+
mask,
|
|
749
|
+
)
|
|
750
|
+
|
|
751
|
+
mel_outputs += [mel_output.squeeze(1)]
|
|
752
|
+
gate_outputs += [gate_output.squeeze(1)]
|
|
753
|
+
alignments += [attention_weights]
|
|
754
|
+
|
|
755
|
+
mel_specgram, gate_outputs, alignments = self._parse_decoder_outputs(
|
|
756
|
+
torch.stack(mel_outputs), torch.stack(gate_outputs), torch.stack(alignments)
|
|
757
|
+
)
|
|
758
|
+
|
|
759
|
+
return mel_specgram, gate_outputs, alignments
|
|
760
|
+
|
|
761
|
+
def _get_go_frame(self, memory: Tensor) -> Tensor:
|
|
762
|
+
"""Gets all zeros frames to use as the first decoder input
|
|
763
|
+
|
|
764
|
+
args:
|
|
765
|
+
memory (Tensor): Encoder outputs
|
|
766
|
+
with shape (n_batch, max of ``text_lengths``, ``encoder_embedding_dim``).
|
|
767
|
+
|
|
768
|
+
returns:
|
|
769
|
+
decoder_input (Tensor): All zeros frames with shape(n_batch, ``n_mels`` * ``n_frame_per_step``).
|
|
770
|
+
"""
|
|
771
|
+
|
|
772
|
+
n_batch = memory.size(0)
|
|
773
|
+
dtype = memory.dtype
|
|
774
|
+
device = memory.device
|
|
775
|
+
decoder_input = torch.zeros(n_batch, self.n_mels * self.n_frames_per_step, dtype=dtype, device=device)
|
|
776
|
+
return decoder_input
|
|
777
|
+
|
|
778
|
+
@torch.jit.export
|
|
779
|
+
def infer(self, memory: Tensor, memory_lengths: Tensor) -> Tuple[Tensor, Tensor, Tensor, Tensor]:
|
|
780
|
+
"""Decoder inference
|
|
781
|
+
|
|
782
|
+
Args:
|
|
783
|
+
memory (Tensor): Encoder outputs
|
|
784
|
+
with shape (n_batch, max of ``text_lengths``, ``encoder_embedding_dim``).
|
|
785
|
+
memory_lengths (Tensor): Encoder output lengths for attention masking
|
|
786
|
+
(the same as ``text_lengths``) with shape (n_batch, ).
|
|
787
|
+
|
|
788
|
+
Returns:
|
|
789
|
+
mel_specgram (Tensor): Predicted mel spectrogram
|
|
790
|
+
with shape (n_batch, ``n_mels``, max of ``mel_specgram_lengths``).
|
|
791
|
+
mel_specgram_lengths (Tensor): the length of the predicted mel spectrogram (n_batch, ))
|
|
792
|
+
gate_outputs (Tensor): Predicted stop token for each timestep
|
|
793
|
+
with shape (n_batch, max of ``mel_specgram_lengths``).
|
|
794
|
+
alignments (Tensor): Sequence of attention weights from the decoder
|
|
795
|
+
with shape (n_batch, max of ``mel_specgram_lengths``, max of ``text_lengths``).
|
|
796
|
+
"""
|
|
797
|
+
batch_size, device = memory.size(0), memory.device
|
|
798
|
+
|
|
799
|
+
decoder_input = self._get_go_frame(memory)
|
|
800
|
+
|
|
801
|
+
mask = _get_mask_from_lengths(memory_lengths)
|
|
802
|
+
(
|
|
803
|
+
attention_hidden,
|
|
804
|
+
attention_cell,
|
|
805
|
+
decoder_hidden,
|
|
806
|
+
decoder_cell,
|
|
807
|
+
attention_weights,
|
|
808
|
+
attention_weights_cum,
|
|
809
|
+
attention_context,
|
|
810
|
+
processed_memory,
|
|
811
|
+
) = self._initialize_decoder_states(memory)
|
|
812
|
+
|
|
813
|
+
mel_specgram_lengths = torch.zeros([batch_size], dtype=torch.int32, device=device)
|
|
814
|
+
finished = torch.zeros([batch_size], dtype=torch.bool, device=device)
|
|
815
|
+
mel_specgrams: List[Tensor] = []
|
|
816
|
+
gate_outputs: List[Tensor] = []
|
|
817
|
+
alignments: List[Tensor] = []
|
|
818
|
+
for _ in range(self.decoder_max_step):
|
|
819
|
+
decoder_input = self.prenet(decoder_input)
|
|
820
|
+
(
|
|
821
|
+
mel_specgram,
|
|
822
|
+
gate_output,
|
|
823
|
+
attention_hidden,
|
|
824
|
+
attention_cell,
|
|
825
|
+
decoder_hidden,
|
|
826
|
+
decoder_cell,
|
|
827
|
+
attention_weights,
|
|
828
|
+
attention_weights_cum,
|
|
829
|
+
attention_context,
|
|
830
|
+
) = self.decode(
|
|
831
|
+
decoder_input,
|
|
832
|
+
attention_hidden,
|
|
833
|
+
attention_cell,
|
|
834
|
+
decoder_hidden,
|
|
835
|
+
decoder_cell,
|
|
836
|
+
attention_weights,
|
|
837
|
+
attention_weights_cum,
|
|
838
|
+
attention_context,
|
|
839
|
+
memory,
|
|
840
|
+
processed_memory,
|
|
841
|
+
mask,
|
|
842
|
+
)
|
|
843
|
+
|
|
844
|
+
mel_specgrams.append(mel_specgram.unsqueeze(0))
|
|
845
|
+
gate_outputs.append(gate_output.transpose(0, 1))
|
|
846
|
+
alignments.append(attention_weights)
|
|
847
|
+
mel_specgram_lengths[~finished] += 1
|
|
848
|
+
|
|
849
|
+
finished |= torch.sigmoid(gate_output.squeeze(1)) > self.gate_threshold
|
|
850
|
+
if self.decoder_early_stopping and torch.all(finished):
|
|
851
|
+
break
|
|
852
|
+
|
|
853
|
+
decoder_input = mel_specgram
|
|
854
|
+
|
|
855
|
+
if len(mel_specgrams) == self.decoder_max_step:
|
|
856
|
+
warnings.warn(
|
|
857
|
+
"Reached max decoder steps. The generated spectrogram might not cover " "the whole transcript."
|
|
858
|
+
)
|
|
859
|
+
|
|
860
|
+
mel_specgrams = torch.cat(mel_specgrams, dim=0)
|
|
861
|
+
gate_outputs = torch.cat(gate_outputs, dim=0)
|
|
862
|
+
alignments = torch.cat(alignments, dim=0)
|
|
863
|
+
|
|
864
|
+
mel_specgrams, gate_outputs, alignments = self._parse_decoder_outputs(mel_specgrams, gate_outputs, alignments)
|
|
865
|
+
|
|
866
|
+
return mel_specgrams, mel_specgram_lengths, gate_outputs, alignments
|
|
867
|
+
|
|
868
|
+
|
|
869
|
+
class Tacotron2(nn.Module):
|
|
870
|
+
r"""Tacotron2 model from *Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions*
|
|
871
|
+
:cite:`shen2018natural` based on the implementation from
|
|
872
|
+
`Nvidia Deep Learning Examples <https://github.com/NVIDIA/DeepLearningExamples/>`_.
|
|
873
|
+
|
|
874
|
+
See Also:
|
|
875
|
+
* :class:`torchaudio.pipelines.Tacotron2TTSBundle`: TTS pipeline with pretrained model.
|
|
876
|
+
|
|
877
|
+
Args:
|
|
878
|
+
mask_padding (bool, optional): Use mask padding (Default: ``False``).
|
|
879
|
+
n_mels (int, optional): Number of mel bins (Default: ``80``).
|
|
880
|
+
n_symbol (int, optional): Number of symbols for the input text (Default: ``148``).
|
|
881
|
+
n_frames_per_step (int, optional): Number of frames processed per step, only 1 is supported (Default: ``1``).
|
|
882
|
+
symbol_embedding_dim (int, optional): Input embedding dimension (Default: ``512``).
|
|
883
|
+
encoder_n_convolution (int, optional): Number of encoder convolutions (Default: ``3``).
|
|
884
|
+
encoder_kernel_size (int, optional): Encoder kernel size (Default: ``5``).
|
|
885
|
+
encoder_embedding_dim (int, optional): Encoder embedding dimension (Default: ``512``).
|
|
886
|
+
decoder_rnn_dim (int, optional): Number of units in decoder LSTM (Default: ``1024``).
|
|
887
|
+
decoder_max_step (int, optional): Maximum number of output mel spectrograms (Default: ``2000``).
|
|
888
|
+
decoder_dropout (float, optional): Dropout probability for decoder LSTM (Default: ``0.1``).
|
|
889
|
+
decoder_early_stopping (bool, optional): Continue decoding after all samples are finished (Default: ``True``).
|
|
890
|
+
attention_rnn_dim (int, optional): Number of units in attention LSTM (Default: ``1024``).
|
|
891
|
+
attention_hidden_dim (int, optional): Dimension of attention hidden representation (Default: ``128``).
|
|
892
|
+
attention_location_n_filter (int, optional): Number of filters for attention model (Default: ``32``).
|
|
893
|
+
attention_location_kernel_size (int, optional): Kernel size for attention model (Default: ``31``).
|
|
894
|
+
attention_dropout (float, optional): Dropout probability for attention LSTM (Default: ``0.1``).
|
|
895
|
+
prenet_dim (int, optional): Number of ReLU units in prenet layers (Default: ``256``).
|
|
896
|
+
postnet_n_convolution (int, optional): Number of postnet convolutions (Default: ``5``).
|
|
897
|
+
postnet_kernel_size (int, optional): Postnet kernel size (Default: ``5``).
|
|
898
|
+
postnet_embedding_dim (int, optional): Postnet embedding dimension (Default: ``512``).
|
|
899
|
+
gate_threshold (float, optional): Probability threshold for stop token (Default: ``0.5``).
|
|
900
|
+
"""
|
|
901
|
+
|
|
902
|
+
def __init__(
|
|
903
|
+
self,
|
|
904
|
+
mask_padding: bool = False,
|
|
905
|
+
n_mels: int = 80,
|
|
906
|
+
n_symbol: int = 148,
|
|
907
|
+
n_frames_per_step: int = 1,
|
|
908
|
+
symbol_embedding_dim: int = 512,
|
|
909
|
+
encoder_embedding_dim: int = 512,
|
|
910
|
+
encoder_n_convolution: int = 3,
|
|
911
|
+
encoder_kernel_size: int = 5,
|
|
912
|
+
decoder_rnn_dim: int = 1024,
|
|
913
|
+
decoder_max_step: int = 2000,
|
|
914
|
+
decoder_dropout: float = 0.1,
|
|
915
|
+
decoder_early_stopping: bool = True,
|
|
916
|
+
attention_rnn_dim: int = 1024,
|
|
917
|
+
attention_hidden_dim: int = 128,
|
|
918
|
+
attention_location_n_filter: int = 32,
|
|
919
|
+
attention_location_kernel_size: int = 31,
|
|
920
|
+
attention_dropout: float = 0.1,
|
|
921
|
+
prenet_dim: int = 256,
|
|
922
|
+
postnet_n_convolution: int = 5,
|
|
923
|
+
postnet_kernel_size: int = 5,
|
|
924
|
+
postnet_embedding_dim: int = 512,
|
|
925
|
+
gate_threshold: float = 0.5,
|
|
926
|
+
) -> None:
|
|
927
|
+
super().__init__()
|
|
928
|
+
|
|
929
|
+
self.mask_padding = mask_padding
|
|
930
|
+
self.n_mels = n_mels
|
|
931
|
+
self.n_frames_per_step = n_frames_per_step
|
|
932
|
+
self.embedding = nn.Embedding(n_symbol, symbol_embedding_dim)
|
|
933
|
+
torch.nn.init.xavier_uniform_(self.embedding.weight)
|
|
934
|
+
self.encoder = _Encoder(encoder_embedding_dim, encoder_n_convolution, encoder_kernel_size)
|
|
935
|
+
self.decoder = _Decoder(
|
|
936
|
+
n_mels,
|
|
937
|
+
n_frames_per_step,
|
|
938
|
+
encoder_embedding_dim,
|
|
939
|
+
decoder_rnn_dim,
|
|
940
|
+
decoder_max_step,
|
|
941
|
+
decoder_dropout,
|
|
942
|
+
decoder_early_stopping,
|
|
943
|
+
attention_rnn_dim,
|
|
944
|
+
attention_hidden_dim,
|
|
945
|
+
attention_location_n_filter,
|
|
946
|
+
attention_location_kernel_size,
|
|
947
|
+
attention_dropout,
|
|
948
|
+
prenet_dim,
|
|
949
|
+
gate_threshold,
|
|
950
|
+
)
|
|
951
|
+
self.postnet = _Postnet(n_mels, postnet_embedding_dim, postnet_kernel_size, postnet_n_convolution)
|
|
952
|
+
|
|
953
|
+
def forward(
|
|
954
|
+
self,
|
|
955
|
+
tokens: Tensor,
|
|
956
|
+
token_lengths: Tensor,
|
|
957
|
+
mel_specgram: Tensor,
|
|
958
|
+
mel_specgram_lengths: Tensor,
|
|
959
|
+
) -> Tuple[Tensor, Tensor, Tensor, Tensor]:
|
|
960
|
+
r"""Pass the input through the Tacotron2 model. This is in teacher
|
|
961
|
+
forcing mode, which is generally used for training.
|
|
962
|
+
|
|
963
|
+
The input ``tokens`` should be padded with zeros to length max of ``token_lengths``.
|
|
964
|
+
The input ``mel_specgram`` should be padded with zeros to length max of ``mel_specgram_lengths``.
|
|
965
|
+
|
|
966
|
+
Args:
|
|
967
|
+
tokens (Tensor): The input tokens to Tacotron2 with shape `(n_batch, max of token_lengths)`.
|
|
968
|
+
token_lengths (Tensor): The valid length of each sample in ``tokens`` with shape `(n_batch, )`.
|
|
969
|
+
mel_specgram (Tensor): The target mel spectrogram
|
|
970
|
+
with shape `(n_batch, n_mels, max of mel_specgram_lengths)`.
|
|
971
|
+
mel_specgram_lengths (Tensor): The length of each mel spectrogram with shape `(n_batch, )`.
|
|
972
|
+
|
|
973
|
+
Returns:
|
|
974
|
+
[Tensor, Tensor, Tensor, Tensor]:
|
|
975
|
+
Tensor
|
|
976
|
+
Mel spectrogram before Postnet with shape `(n_batch, n_mels, max of mel_specgram_lengths)`.
|
|
977
|
+
Tensor
|
|
978
|
+
Mel spectrogram after Postnet with shape `(n_batch, n_mels, max of mel_specgram_lengths)`.
|
|
979
|
+
Tensor
|
|
980
|
+
The output for stop token at each time step with shape `(n_batch, max of mel_specgram_lengths)`.
|
|
981
|
+
Tensor
|
|
982
|
+
Sequence of attention weights from the decoder with
|
|
983
|
+
shape `(n_batch, max of mel_specgram_lengths, max of token_lengths)`.
|
|
984
|
+
"""
|
|
985
|
+
|
|
986
|
+
embedded_inputs = self.embedding(tokens).transpose(1, 2)
|
|
987
|
+
|
|
988
|
+
encoder_outputs = self.encoder(embedded_inputs, token_lengths)
|
|
989
|
+
mel_specgram, gate_outputs, alignments = self.decoder(
|
|
990
|
+
encoder_outputs, mel_specgram, memory_lengths=token_lengths
|
|
991
|
+
)
|
|
992
|
+
|
|
993
|
+
mel_specgram_postnet = self.postnet(mel_specgram)
|
|
994
|
+
mel_specgram_postnet = mel_specgram + mel_specgram_postnet
|
|
995
|
+
|
|
996
|
+
if self.mask_padding:
|
|
997
|
+
mask = _get_mask_from_lengths(mel_specgram_lengths)
|
|
998
|
+
mask = mask.expand(self.n_mels, mask.size(0), mask.size(1))
|
|
999
|
+
mask = mask.permute(1, 0, 2)
|
|
1000
|
+
|
|
1001
|
+
mel_specgram.masked_fill_(mask, 0.0)
|
|
1002
|
+
mel_specgram_postnet.masked_fill_(mask, 0.0)
|
|
1003
|
+
gate_outputs.masked_fill_(mask[:, 0, :], 1e3)
|
|
1004
|
+
|
|
1005
|
+
return mel_specgram, mel_specgram_postnet, gate_outputs, alignments
|
|
1006
|
+
|
|
1007
|
+
@torch.jit.export
|
|
1008
|
+
def infer(self, tokens: Tensor, lengths: Optional[Tensor] = None) -> Tuple[Tensor, Tensor, Tensor]:
|
|
1009
|
+
r"""Using Tacotron2 for inference. The input is a batch of encoded
|
|
1010
|
+
sentences (``tokens``) and its corresponding lengths (``lengths``). The
|
|
1011
|
+
output is the generated mel spectrograms, its corresponding lengths, and
|
|
1012
|
+
the attention weights from the decoder.
|
|
1013
|
+
|
|
1014
|
+
The input `tokens` should be padded with zeros to length max of ``lengths``.
|
|
1015
|
+
|
|
1016
|
+
Args:
|
|
1017
|
+
tokens (Tensor): The input tokens to Tacotron2 with shape `(n_batch, max of lengths)`.
|
|
1018
|
+
lengths (Tensor or None, optional):
|
|
1019
|
+
The valid length of each sample in ``tokens`` with shape `(n_batch, )`.
|
|
1020
|
+
If ``None``, it is assumed that the all the tokens are valid. Default: ``None``
|
|
1021
|
+
|
|
1022
|
+
Returns:
|
|
1023
|
+
(Tensor, Tensor, Tensor):
|
|
1024
|
+
Tensor
|
|
1025
|
+
The predicted mel spectrogram with shape `(n_batch, n_mels, max of mel_specgram_lengths)`.
|
|
1026
|
+
Tensor
|
|
1027
|
+
The length of the predicted mel spectrogram with shape `(n_batch, )`.
|
|
1028
|
+
Tensor
|
|
1029
|
+
Sequence of attention weights from the decoder with shape
|
|
1030
|
+
`(n_batch, max of mel_specgram_lengths, max of lengths)`.
|
|
1031
|
+
"""
|
|
1032
|
+
n_batch, max_length = tokens.shape
|
|
1033
|
+
if lengths is None:
|
|
1034
|
+
lengths = torch.tensor([max_length]).expand(n_batch).to(tokens.device, tokens.dtype)
|
|
1035
|
+
|
|
1036
|
+
assert lengths is not None # For TorchScript compiler
|
|
1037
|
+
embedded_inputs = self.embedding(tokens).transpose(1, 2)
|
|
1038
|
+
encoder_outputs = self.encoder(embedded_inputs, lengths)
|
|
1039
|
+
mel_specgram, mel_specgram_lengths, _, alignments = self.decoder.infer(encoder_outputs, lengths)
|
|
1040
|
+
|
|
1041
|
+
mel_outputs_postnet = self.postnet(mel_specgram)
|
|
1042
|
+
mel_outputs_postnet = mel_specgram + mel_outputs_postnet
|
|
1043
|
+
|
|
1044
|
+
alignments = alignments.unfold(1, n_batch, n_batch).transpose(0, 2)
|
|
1045
|
+
|
|
1046
|
+
return mel_outputs_postnet, mel_specgram_lengths, alignments
|