muhtasham commited on
Commit
9d199d5
·
1 Parent(s): 2aae7e6
Files changed (3) hide show
  1. README.md +14 -35
  2. config.json +13 -0
  3. hifigan_ar_v2.py +1180 -0
README.md CHANGED
@@ -9,46 +9,25 @@ tags:
9
  - tts
10
  ---
11
 
12
- # HiFiGAN Finetuned Checkpoint
13
 
14
- This is a finetuned HiFiGAN model checkpoint for vocoder.
15
-
16
- ## Model Details
17
- - Base Model: HiFiGAN
18
- - Training Type: Finetuned from HuggingFace checkpoint
19
- - Sample Rate: 22050 Hz
20
- - Checkpoint Date: 2025-03-30
21
-
22
- ## Files
23
- - `generator.ckpt`: The model weights
24
- - `hyperparams.yaml`: Model hyperparameters
25
 
26
  ## Usage
 
27
  ```python
28
- from speechbrain.lobes.models.HifiGAN import HifiganGenerator
29
  import torch
30
- from hyperpyyaml import load_hyperpyyaml
31
 
32
- # Load hyperparameters
33
- with open("hyperparams.yaml") as f:
34
- hparams = load_hyperpyyaml(f)
35
 
36
- # Initialize generator
37
- generator = HifiganGenerator(
38
- in_channels=hparams["in_channels"],
39
- out_channels=hparams["out_channels"],
40
- resblock_type=hparams["resblock_type"],
41
- resblock_dilation_sizes=hparams["resblock_dilation_sizes"],
42
- resblock_kernel_sizes=hparams["resblock_kernel_sizes"],
43
- upsample_kernel_sizes=hparams["upsample_kernel_sizes"],
44
- upsample_initial_channel=hparams["upsample_initial_channel"],
45
- upsample_factors=hparams["upsample_factors"],
46
- inference_padding=hparams["inference_padding"],
47
- cond_channels=hparams["cond_channels"],
48
- conv_post_bias=hparams["conv_post_bias"],
49
- )
50
-
51
- # Load checkpoint
52
- generator.load_state_dict(torch.load("generator.ckpt"))
53
- generator.eval()
54
  ```
 
 
 
 
 
 
9
  - tts
10
  ---
11
 
12
+ # HiFiGAN Arabic Vocoder
13
 
14
+ A standalone implementation of HiFiGAN vocoder for Arabic text-to-speech, based on the paper "HiFi-GAN: Generative Adversarial Networks for Efficient and High Fidelity Speech Synthesis" (https://arxiv.org/pdf/2010.05646.pdf).
 
 
 
 
 
 
 
 
 
 
15
 
16
  ## Usage
17
+
18
  ```python
19
+ from hifigan_ar_v2 import HiFiGANArabicGenerator
20
  import torch
 
21
 
22
+ # Load the model
23
+ model = HiFiGANArabicGenerator.from_pretrained("generator.ckpt", "config.json")
 
24
 
25
+ # Generate audio from mel spectrogram
26
+ mel = torch.rand(1, 80, 122) # Example mel spectrogram
27
+ audio = model(mel) # Shape: [1, 1, 8448]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  ```
29
+
30
+ ## Model Details
31
+ - Sample Rate: 22050 Hz
32
+ - Input: Mel spectrogram (80 channels)
33
+ - Output: Audio waveform (1 channel)
config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "in_channels": 80,
3
+ "out_channels": 1,
4
+ "resblock_type": "1",
5
+ "resblock_dilation_sizes": [[1, 3, 5], [1, 3, 5], [1, 3, 5]],
6
+ "resblock_kernel_sizes": [3, 7, 11],
7
+ "upsample_kernel_sizes": [16, 16, 4, 4],
8
+ "upsample_initial_channel": 512,
9
+ "upsample_factors": [8, 8, 2, 2],
10
+ "inference_padding": 5,
11
+ "cond_channels": 0,
12
+ "conv_post_bias": true
13
+ }
hifigan_ar_v2.py ADDED
@@ -0,0 +1,1180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Neural network modules for the HiFi-GAN: Generative Adversarial Networks for
3
+ Efficient and High Fidelity Speech Synthesis
4
+
5
+ For more details: https://arxiv.org/pdf/2010.05646.pdf, https://arxiv.org/abs/2406.10735
6
+
7
+ Authors
8
+ * Jarod Duret 2021
9
+ * Yingzhi WANG 2022
10
+ """
11
+
12
+ # Adapted from https://github.com/jik876/hifi-gan/ and https://github.com/coqui-ai/TTS/
13
+ # MIT License
14
+
15
+ # Copyright (c) 2020 Jungil Kong
16
+
17
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
18
+ # of this software and associated documentation files (the "Software"), to deal
19
+ # in the Software without restriction, including without limitation the rights
20
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
21
+ # copies of the Software, and to permit persons to whom the Software is
22
+ # furnished to do so, subject to the following conditions:
23
+
24
+ # The above copyright notice and this permission notice shall be included in all
25
+ # copies or substantial portions of the Software.
26
+
27
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
28
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
29
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
30
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
31
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
32
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
33
+ # SOFTWARE.
34
+
35
+
36
+ import json
37
+ import logging
38
+ import math
39
+ import os
40
+ from typing import Tuple
41
+
42
+ import torch
43
+ import torch.nn as nn
44
+ import torch.nn.functional as F
45
+
46
+
47
+ LRELU_SLOPE = 0.1
48
+
49
+
50
+ def get_padding_elem(L_in: int, stride: int, kernel_size: int, dilation: int):
51
+ """This function computes the number of elements to add for zero-padding.
52
+
53
+ Arguments
54
+ ---------
55
+ L_in : int
56
+ stride: int
57
+ kernel_size : int
58
+ dilation : int
59
+
60
+ Returns
61
+ -------
62
+ padding : int
63
+ The size of the padding to be added
64
+ """
65
+ if stride > 1:
66
+ padding = [math.floor(kernel_size / 2), math.floor(kernel_size / 2)]
67
+
68
+ else:
69
+ L_out = (
70
+ math.floor((L_in - dilation * (kernel_size - 1) - 1) / stride) + 1
71
+ )
72
+ padding = [
73
+ math.floor((L_in - L_out) / 2),
74
+ math.floor((L_in - L_out) / 2),
75
+ ]
76
+ return padding
77
+
78
+
79
+ def get_padding_elem_transposed(
80
+ L_out: int,
81
+ L_in: int,
82
+ stride: int,
83
+ kernel_size: int,
84
+ dilation: int,
85
+ output_padding: int,
86
+ ):
87
+ """This function computes the required padding size for transposed convolution
88
+
89
+ Arguments
90
+ ---------
91
+ L_out : int
92
+ L_in : int
93
+ stride: int
94
+ kernel_size : int
95
+ dilation : int
96
+ output_padding : int
97
+
98
+ Returns
99
+ -------
100
+ padding : int
101
+ The size of the padding to be applied
102
+ """
103
+
104
+ padding = -0.5 * (
105
+ L_out
106
+ - (L_in - 1) * stride
107
+ - dilation * (kernel_size - 1)
108
+ - output_padding
109
+ - 1
110
+ )
111
+ return int(padding)
112
+
113
+
114
+ class Conv1d(nn.Module):
115
+ """This function implements 1d convolution.
116
+
117
+ Arguments
118
+ ---------
119
+ out_channels : int
120
+ It is the number of output channels.
121
+ kernel_size : int
122
+ Kernel size of the convolutional filters.
123
+ input_shape : tuple
124
+ The shape of the input. Alternatively use ``in_channels``.
125
+ in_channels : int
126
+ The number of input channels. Alternatively use ``input_shape``.
127
+ stride : int
128
+ Stride factor of the convolutional filters. When the stride factor > 1,
129
+ a decimation in time is performed.
130
+ dilation : int
131
+ Dilation factor of the convolutional filters.
132
+ padding : str
133
+ (same, valid, causal). If "valid", no padding is performed.
134
+ If "same" and stride is 1, output shape is the same as the input shape.
135
+ "causal" results in causal (dilated) convolutions.
136
+ groups : int
137
+ Number of blocked connections from input channels to output channels.
138
+ bias : bool
139
+ Whether to add a bias term to convolution operation.
140
+ padding_mode : str
141
+ This flag specifies the type of padding. See torch.nn documentation
142
+ for more information.
143
+ skip_transpose : bool
144
+ If False, uses batch x time x channel convention of speechbrain.
145
+ If True, uses batch x channel x time convention.
146
+ weight_norm : bool
147
+ If True, use weight normalization,
148
+ to be removed with self.remove_weight_norm() at inference
149
+ conv_init : str
150
+ Weight initialization for the convolution network
151
+ default_padding: str or int
152
+ This sets the default padding mode that will be used by the pytorch Conv1d backend.
153
+
154
+ Example
155
+ -------
156
+ >>> inp_tensor = torch.rand([10, 40, 16])
157
+ >>> cnn_1d = Conv1d(
158
+ ... input_shape=inp_tensor.shape, out_channels=8, kernel_size=5
159
+ ... )
160
+ >>> out_tensor = cnn_1d(inp_tensor)
161
+ >>> out_tensor.shape
162
+ torch.Size([10, 40, 8])
163
+ """
164
+
165
+ def __init__(
166
+ self,
167
+ out_channels,
168
+ kernel_size,
169
+ input_shape=None,
170
+ in_channels=None,
171
+ stride=1,
172
+ dilation=1,
173
+ padding="same",
174
+ groups=1,
175
+ bias=True,
176
+ padding_mode="reflect",
177
+ skip_transpose=False,
178
+ weight_norm=False,
179
+ conv_init=None,
180
+ default_padding=0,
181
+ ):
182
+ super().__init__()
183
+ self.kernel_size = kernel_size
184
+ self.stride = stride
185
+ self.dilation = dilation
186
+ self.padding = padding
187
+ self.padding_mode = padding_mode
188
+ self.unsqueeze = False
189
+ self.skip_transpose = skip_transpose
190
+
191
+ if input_shape is None and in_channels is None:
192
+ raise ValueError("Must provide one of input_shape or in_channels")
193
+
194
+ if in_channels is None:
195
+ in_channels = self._check_input_shape(input_shape)
196
+
197
+ self.in_channels = in_channels
198
+
199
+ self.conv = nn.Conv1d(
200
+ in_channels,
201
+ out_channels,
202
+ self.kernel_size,
203
+ stride=self.stride,
204
+ dilation=self.dilation,
205
+ padding=default_padding,
206
+ groups=groups,
207
+ bias=bias,
208
+ )
209
+
210
+ if conv_init == "kaiming":
211
+ nn.init.kaiming_normal_(self.conv.weight)
212
+ elif conv_init == "zero":
213
+ nn.init.zeros_(self.conv.weight)
214
+ elif conv_init == "normal":
215
+ nn.init.normal_(self.conv.weight, std=1e-6)
216
+
217
+ if weight_norm:
218
+ self.conv = nn.utils.weight_norm(self.conv)
219
+
220
+ def forward(self, x):
221
+ """Returns the output of the convolution.
222
+
223
+ Arguments
224
+ ---------
225
+ x : torch.Tensor (batch, time, channel)
226
+ input to convolve. 2d or 4d tensors are expected.
227
+
228
+ Returns
229
+ -------
230
+ wx : torch.Tensor
231
+ The convolved outputs.
232
+ """
233
+ if not self.skip_transpose:
234
+ x = x.transpose(1, -1)
235
+
236
+ if self.unsqueeze:
237
+ x = x.unsqueeze(1)
238
+
239
+ if self.padding == "same":
240
+ x = self._manage_padding(
241
+ x, self.kernel_size, self.dilation, self.stride
242
+ )
243
+
244
+ elif self.padding == "causal":
245
+ num_pad = (self.kernel_size - 1) * self.dilation
246
+ x = F.pad(x, (num_pad, 0))
247
+
248
+ elif self.padding == "valid":
249
+ pass
250
+
251
+ else:
252
+ raise ValueError(
253
+ "Padding must be 'same', 'valid' or 'causal'. Got "
254
+ + self.padding
255
+ )
256
+
257
+ wx = self.conv(x)
258
+
259
+ if self.unsqueeze:
260
+ wx = wx.squeeze(1)
261
+
262
+ if not self.skip_transpose:
263
+ wx = wx.transpose(1, -1)
264
+
265
+ return wx
266
+
267
+ def _manage_padding(self, x, kernel_size: int, dilation: int, stride: int):
268
+ """This function performs zero-padding on the time axis
269
+ such that their lengths is unchanged after the convolution.
270
+
271
+ Arguments
272
+ ---------
273
+ x : torch.Tensor
274
+ Input tensor.
275
+ kernel_size : int
276
+ Size of kernel.
277
+ dilation : int
278
+ Dilation used.
279
+ stride : int
280
+ Stride.
281
+
282
+ Returns
283
+ -------
284
+ x : torch.Tensor
285
+ The padded outputs.
286
+ """
287
+
288
+ # Detecting input shape
289
+ L_in = self.in_channels
290
+
291
+ # Time padding
292
+ padding = get_padding_elem(L_in, stride, kernel_size, dilation)
293
+
294
+ # Applying padding
295
+ x = F.pad(x, padding, mode=self.padding_mode)
296
+
297
+ return x
298
+
299
+ def _check_input_shape(self, shape):
300
+ """Checks the input shape and returns the number of input channels."""
301
+
302
+ if len(shape) == 2:
303
+ self.unsqueeze = True
304
+ in_channels = 1
305
+ elif self.skip_transpose:
306
+ in_channels = shape[1]
307
+ elif len(shape) == 3:
308
+ in_channels = shape[2]
309
+ else:
310
+ raise ValueError(
311
+ "conv1d expects 2d, 3d inputs. Got " + str(len(shape))
312
+ )
313
+
314
+ # Kernel size must be odd
315
+ if not self.padding == "valid" and self.kernel_size % 2 == 0:
316
+ raise ValueError(
317
+ "The field kernel size must be an odd number. Got %s."
318
+ % (self.kernel_size)
319
+ )
320
+
321
+ return in_channels
322
+
323
+ def remove_weight_norm(self):
324
+ """Removes weight normalization at inference if used during training."""
325
+ self.conv = nn.utils.remove_weight_norm(self.conv)
326
+
327
+
328
+ class Conv2d(nn.Module):
329
+ """This function implements 2d convolution.
330
+
331
+ Arguments
332
+ ---------
333
+ out_channels : int
334
+ It is the number of output channels.
335
+ kernel_size : tuple
336
+ Kernel size of the 2d convolutional filters over time and frequency
337
+ axis.
338
+ input_shape : tuple
339
+ The shape of the input. Alternatively use ``in_channels``.
340
+ in_channels : int
341
+ The number of input channels. Alternatively use ``input_shape``.
342
+ stride: int
343
+ Stride factor of the 2d convolutional filters over time and frequency
344
+ axis.
345
+ dilation : int
346
+ Dilation factor of the 2d convolutional filters over time and
347
+ frequency axis.
348
+ padding : str
349
+ (same, valid, causal).
350
+ If "valid", no padding is performed.
351
+ If "same" and stride is 1, output shape is same as input shape.
352
+ If "causal" then proper padding is inserted to simulate causal convolution on the first spatial dimension.
353
+ (spatial dim 1 is dim 3 for both skip_transpose=False and skip_transpose=True)
354
+ groups : int
355
+ This option specifies the convolutional groups. See torch.nn
356
+ documentation for more information.
357
+ bias : bool
358
+ If True, the additive bias b is adopted.
359
+ padding_mode : str
360
+ This flag specifies the type of padding. See torch.nn documentation
361
+ for more information.
362
+ max_norm : float
363
+ kernel max-norm.
364
+ swap : bool
365
+ If True, the convolution is done with the format (B, C, W, H).
366
+ If False, the convolution is dine with (B, H, W, C).
367
+ Active only if skip_transpose is False.
368
+ skip_transpose : bool
369
+ If False, uses batch x spatial.dim2 x spatial.dim1 x channel convention of speechbrain.
370
+ If True, uses batch x channel x spatial.dim1 x spatial.dim2 convention.
371
+ weight_norm : bool
372
+ If True, use weight normalization,
373
+ to be removed with self.remove_weight_norm() at inference
374
+ conv_init : str
375
+ Weight initialization for the convolution network
376
+
377
+ Example
378
+ -------
379
+ >>> inp_tensor = torch.rand([10, 40, 16, 8])
380
+ >>> cnn_2d = Conv2d(
381
+ ... input_shape=inp_tensor.shape, out_channels=5, kernel_size=(7, 3)
382
+ ... )
383
+ >>> out_tensor = cnn_2d(inp_tensor)
384
+ >>> out_tensor.shape
385
+ torch.Size([10, 40, 16, 5])
386
+ """
387
+
388
+ def __init__(
389
+ self,
390
+ out_channels,
391
+ kernel_size,
392
+ input_shape=None,
393
+ in_channels=None,
394
+ stride=(1, 1),
395
+ dilation=(1, 1),
396
+ padding="same",
397
+ groups=1,
398
+ bias=True,
399
+ padding_mode="reflect",
400
+ max_norm=None,
401
+ swap=False,
402
+ skip_transpose=False,
403
+ weight_norm=False,
404
+ conv_init=None,
405
+ ):
406
+ super().__init__()
407
+
408
+ # handle the case if some parameter is int
409
+ if isinstance(kernel_size, int):
410
+ kernel_size = (kernel_size, kernel_size)
411
+ if isinstance(stride, int):
412
+ stride = (stride, stride)
413
+ if isinstance(dilation, int):
414
+ dilation = (dilation, dilation)
415
+
416
+ self.kernel_size = kernel_size
417
+ self.stride = stride
418
+ self.dilation = dilation
419
+ self.padding = padding
420
+ self.padding_mode = padding_mode
421
+ self.unsqueeze = False
422
+ self.max_norm = max_norm
423
+ self.swap = swap
424
+ self.skip_transpose = skip_transpose
425
+
426
+ if input_shape is None and in_channels is None:
427
+ raise ValueError("Must provide one of input_shape or in_channels")
428
+
429
+ if in_channels is None:
430
+ in_channels = self._check_input(input_shape)
431
+
432
+ self.in_channels = in_channels
433
+
434
+ # Weights are initialized following pytorch approach
435
+ self.conv = nn.Conv2d(
436
+ self.in_channels,
437
+ out_channels,
438
+ self.kernel_size,
439
+ stride=self.stride,
440
+ padding=0,
441
+ dilation=self.dilation,
442
+ groups=groups,
443
+ bias=bias,
444
+ )
445
+
446
+ if conv_init == "kaiming":
447
+ nn.init.kaiming_normal_(self.conv.weight)
448
+ elif conv_init == "zero":
449
+ nn.init.zeros_(self.conv.weight)
450
+
451
+ if weight_norm:
452
+ self.conv = nn.utils.weight_norm(self.conv)
453
+
454
+ def forward(self, x):
455
+ """Returns the output of the convolution.
456
+
457
+ Arguments
458
+ ---------
459
+ x : torch.Tensor (batch, time, channel)
460
+ input to convolve. 2d or 4d tensors are expected.
461
+
462
+ Returns
463
+ -------
464
+ x : torch.Tensor
465
+ The output of the convolution.
466
+ """
467
+ if not self.skip_transpose:
468
+ x = x.transpose(1, -1)
469
+ if self.swap:
470
+ x = x.transpose(-1, -2)
471
+
472
+ if self.unsqueeze:
473
+ x = x.unsqueeze(1)
474
+
475
+ if self.padding == "same":
476
+ x = self._manage_padding(
477
+ x, self.kernel_size, self.dilation, self.stride
478
+ )
479
+
480
+ elif self.padding == "causal":
481
+ num_pad = (self.kernel_size[0] - 1) * self.dilation[1]
482
+ x = F.pad(x, (0, 0, num_pad, 0))
483
+
484
+ elif self.padding == "valid":
485
+ pass
486
+
487
+ else:
488
+ raise ValueError(
489
+ "Padding must be 'same','valid' or 'causal'. Got "
490
+ + self.padding
491
+ )
492
+
493
+ if self.max_norm is not None:
494
+ self.conv.weight.data = torch.renorm(
495
+ self.conv.weight.data, p=2, dim=0, maxnorm=self.max_norm
496
+ )
497
+
498
+ wx = self.conv(x)
499
+
500
+ if self.unsqueeze:
501
+ wx = wx.squeeze(1)
502
+
503
+ if not self.skip_transpose:
504
+ wx = wx.transpose(1, -1)
505
+ if self.swap:
506
+ wx = wx.transpose(1, 2)
507
+ return wx
508
+
509
+ def _manage_padding(
510
+ self,
511
+ x,
512
+ kernel_size: Tuple[int, int],
513
+ dilation: Tuple[int, int],
514
+ stride: Tuple[int, int],
515
+ ):
516
+ """This function performs zero-padding on the time and frequency axes
517
+ such that their lengths is unchanged after the convolution.
518
+
519
+ Arguments
520
+ ---------
521
+ x : torch.Tensor
522
+ Input to be padded
523
+ kernel_size : int
524
+ Size of the kernel for computing padding
525
+ dilation : int
526
+ Dilation rate for computing padding
527
+ stride: int
528
+ Stride for computing padding
529
+
530
+ Returns
531
+ -------
532
+ x : torch.Tensor
533
+ The padded outputs.
534
+ """
535
+ # Detecting input shape
536
+ L_in = self.in_channels
537
+
538
+ # Time padding
539
+ padding_time = get_padding_elem(
540
+ L_in, stride[-1], kernel_size[-1], dilation[-1]
541
+ )
542
+
543
+ padding_freq = get_padding_elem(
544
+ L_in, stride[-2], kernel_size[-2], dilation[-2]
545
+ )
546
+ padding = padding_time + padding_freq
547
+
548
+ # Applying padding
549
+ x = nn.functional.pad(x, padding, mode=self.padding_mode)
550
+
551
+ return x
552
+
553
+ def _check_input(self, shape):
554
+ """Checks the input shape and returns the number of input channels."""
555
+
556
+ if len(shape) == 3:
557
+ self.unsqueeze = True
558
+ in_channels = 1
559
+
560
+ elif len(shape) == 4:
561
+ in_channels = shape[3]
562
+
563
+ else:
564
+ raise ValueError("Expected 3d or 4d inputs. Got " + len(shape))
565
+
566
+ # Kernel size must be odd
567
+ if not self.padding == "valid" and (
568
+ self.kernel_size[0] % 2 == 0 or self.kernel_size[1] % 2 == 0
569
+ ):
570
+ raise ValueError(
571
+ "The field kernel size must be an odd number. Got %s."
572
+ % (self.kernel_size)
573
+ )
574
+
575
+ return in_channels
576
+
577
+ def remove_weight_norm(self):
578
+ """Removes weight normalization at inference if used during training."""
579
+ self.conv = nn.utils.remove_weight_norm(self.conv)
580
+
581
+
582
+ class ConvTranspose1d(nn.Module):
583
+ """This class implements 1d transposed convolution with speechbrain.
584
+ Transpose convolution is normally used to perform upsampling.
585
+
586
+ Arguments
587
+ ---------
588
+ out_channels : int
589
+ It is the number of output channels.
590
+ kernel_size : int
591
+ Kernel size of the convolutional filters.
592
+ input_shape : tuple
593
+ The shape of the input. Alternatively use ``in_channels``.
594
+ in_channels : int
595
+ The number of input channels. Alternatively use ``input_shape``.
596
+ stride : int
597
+ Stride factor of the convolutional filters. When the stride factor > 1,
598
+ upsampling in time is performed.
599
+ dilation : int
600
+ Dilation factor of the convolutional filters.
601
+ padding : str or int
602
+ To have in output the target dimension, we suggest tuning the kernel
603
+ size and the padding properly. We also support the following function
604
+ to have some control over the padding and the corresponding output
605
+ dimensionality.
606
+ if "valid", no padding is applied
607
+ if "same", padding amount is inferred so that the output size is closest
608
+ to possible to input size. Note that for some kernel_size / stride combinations
609
+ it is not possible to obtain the exact same size, but we return the closest
610
+ possible size.
611
+ if "factor", padding amount is inferred so that the output size is closest
612
+ to inputsize*stride. Note that for some kernel_size / stride combinations
613
+ it is not possible to obtain the exact size, but we return the closest
614
+ possible size.
615
+ if an integer value is entered, a custom padding is used.
616
+ output_padding : int,
617
+ Additional size added to one side of the output shape
618
+ groups: int
619
+ Number of blocked connections from input channels to output channels.
620
+ Default: 1
621
+ bias: bool
622
+ If True, adds a learnable bias to the output
623
+ skip_transpose : bool
624
+ If False, uses batch x time x channel convention of speechbrain.
625
+ If True, uses batch x channel x time convention.
626
+ weight_norm : bool
627
+ If True, use weight normalization,
628
+ to be removed with self.remove_weight_norm() at inference
629
+
630
+ Example
631
+ -------
632
+ >>> from speechbrain.nnet.CNN import Conv1d, ConvTranspose1d
633
+ >>> inp_tensor = torch.rand([10, 12, 40]) #[batch, time, fea]
634
+ >>> convtranspose_1d = ConvTranspose1d(
635
+ ... input_shape=inp_tensor.shape, out_channels=8, kernel_size=3, stride=2
636
+ ... )
637
+ >>> out_tensor = convtranspose_1d(inp_tensor)
638
+ >>> out_tensor.shape
639
+ torch.Size([10, 25, 8])
640
+
641
+ >>> # Combination of Conv1d and ConvTranspose1d
642
+ >>> from speechbrain.nnet.CNN import Conv1d, ConvTranspose1d
643
+ >>> signal = torch.tensor([1,100])
644
+ >>> signal = torch.rand([1,100]) #[batch, time]
645
+ >>> conv1d = Conv1d(input_shape=signal.shape, out_channels=1, kernel_size=3, stride=2)
646
+ >>> conv_out = conv1d(signal)
647
+ >>> conv_t = ConvTranspose1d(input_shape=conv_out.shape, out_channels=1, kernel_size=3, stride=2, padding=1)
648
+ >>> signal_rec = conv_t(conv_out, output_size=[100])
649
+ >>> signal_rec.shape
650
+ torch.Size([1, 100])
651
+
652
+ >>> signal = torch.rand([1,115]) #[batch, time]
653
+ >>> conv_t = ConvTranspose1d(input_shape=signal.shape, out_channels=1, kernel_size=3, stride=2, padding='same')
654
+ >>> signal_rec = conv_t(signal)
655
+ >>> signal_rec.shape
656
+ torch.Size([1, 115])
657
+
658
+ >>> signal = torch.rand([1,115]) #[batch, time]
659
+ >>> conv_t = ConvTranspose1d(input_shape=signal.shape, out_channels=1, kernel_size=7, stride=2, padding='valid')
660
+ >>> signal_rec = conv_t(signal)
661
+ >>> signal_rec.shape
662
+ torch.Size([1, 235])
663
+
664
+ >>> signal = torch.rand([1,115]) #[batch, time]
665
+ >>> conv_t = ConvTranspose1d(input_shape=signal.shape, out_channels=1, kernel_size=7, stride=2, padding='factor')
666
+ >>> signal_rec = conv_t(signal)
667
+ >>> signal_rec.shape
668
+ torch.Size([1, 231])
669
+
670
+ >>> signal = torch.rand([1,115]) #[batch, time]
671
+ >>> conv_t = ConvTranspose1d(input_shape=signal.shape, out_channels=1, kernel_size=3, stride=2, padding=10)
672
+ >>> signal_rec = conv_t(signal)
673
+ >>> signal_rec.shape
674
+ torch.Size([1, 211])
675
+
676
+ """
677
+
678
+ def __init__(
679
+ self,
680
+ out_channels,
681
+ kernel_size,
682
+ input_shape=None,
683
+ in_channels=None,
684
+ stride=1,
685
+ dilation=1,
686
+ padding=0,
687
+ output_padding=0,
688
+ groups=1,
689
+ bias=True,
690
+ skip_transpose=False,
691
+ weight_norm=False,
692
+ ):
693
+ super().__init__()
694
+ self.kernel_size = kernel_size
695
+ self.stride = stride
696
+ self.dilation = dilation
697
+ self.padding = padding
698
+ self.unsqueeze = False
699
+ self.skip_transpose = skip_transpose
700
+
701
+ if input_shape is None and in_channels is None:
702
+ raise ValueError("Must provide one of input_shape or in_channels")
703
+
704
+ if in_channels is None:
705
+ in_channels = self._check_input_shape(input_shape)
706
+
707
+ if self.padding == "same":
708
+ L_in = input_shape[-1] if skip_transpose else input_shape[1]
709
+ padding_value = get_padding_elem_transposed(
710
+ L_in,
711
+ L_in,
712
+ stride=stride,
713
+ kernel_size=kernel_size,
714
+ dilation=dilation,
715
+ output_padding=output_padding,
716
+ )
717
+ elif self.padding == "factor":
718
+ L_in = input_shape[-1] if skip_transpose else input_shape[1]
719
+ padding_value = get_padding_elem_transposed(
720
+ L_in * stride,
721
+ L_in,
722
+ stride=stride,
723
+ kernel_size=kernel_size,
724
+ dilation=dilation,
725
+ output_padding=output_padding,
726
+ )
727
+ elif self.padding == "valid":
728
+ padding_value = 0
729
+ elif type(self.padding) is int:
730
+ padding_value = padding
731
+ else:
732
+ raise ValueError("Not supported padding type")
733
+
734
+ self.conv = nn.ConvTranspose1d(
735
+ in_channels,
736
+ out_channels,
737
+ self.kernel_size,
738
+ stride=self.stride,
739
+ dilation=self.dilation,
740
+ padding=padding_value,
741
+ groups=groups,
742
+ bias=bias,
743
+ )
744
+
745
+ if weight_norm:
746
+ self.conv = nn.utils.weight_norm(self.conv)
747
+
748
+ def forward(self, x, output_size=None):
749
+ """Returns the output of the convolution.
750
+
751
+ Arguments
752
+ ---------
753
+ x : torch.Tensor (batch, time, channel)
754
+ input to convolve. 2d or 4d tensors are expected.
755
+ output_size : int
756
+ The size of the output
757
+
758
+ Returns
759
+ -------
760
+ x : torch.Tensor
761
+ The convolved output
762
+ """
763
+
764
+ if not self.skip_transpose:
765
+ x = x.transpose(1, -1)
766
+
767
+ if self.unsqueeze:
768
+ x = x.unsqueeze(1)
769
+
770
+ wx = self.conv(x, output_size=output_size)
771
+
772
+ if self.unsqueeze:
773
+ wx = wx.squeeze(1)
774
+
775
+ if not self.skip_transpose:
776
+ wx = wx.transpose(1, -1)
777
+
778
+ return wx
779
+
780
+ def _check_input_shape(self, shape):
781
+ """Checks the input shape and returns the number of input channels."""
782
+
783
+ if len(shape) == 2:
784
+ self.unsqueeze = True
785
+ in_channels = 1
786
+ elif self.skip_transpose:
787
+ in_channels = shape[1]
788
+ elif len(shape) == 3:
789
+ in_channels = shape[2]
790
+ else:
791
+ raise ValueError(
792
+ "conv1d expects 2d, 3d inputs. Got " + str(len(shape))
793
+ )
794
+
795
+ return in_channels
796
+
797
+ def remove_weight_norm(self):
798
+ """Removes weight normalization at inference if used during training."""
799
+ self.conv = nn.utils.remove_weight_norm(self.conv)
800
+
801
+
802
+ class ResBlock1(torch.nn.Module):
803
+ """
804
+ Residual Block Type 1, which has 3 convolutional layers in each convolution block.
805
+
806
+ Arguments
807
+ ---------
808
+ channels : int
809
+ number of hidden channels for the convolutional layers.
810
+ kernel_size : int
811
+ size of the convolution filter in each layer.
812
+ dilation : list
813
+ list of dilation value for each conv layer in a block.
814
+ """
815
+
816
+ def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):
817
+ super().__init__()
818
+ self.convs1 = nn.ModuleList(
819
+ [
820
+ Conv1d(
821
+ in_channels=channels,
822
+ out_channels=channels,
823
+ kernel_size=kernel_size,
824
+ stride=1,
825
+ dilation=dilation[0],
826
+ padding="same",
827
+ skip_transpose=True,
828
+ weight_norm=True,
829
+ ),
830
+ Conv1d(
831
+ in_channels=channels,
832
+ out_channels=channels,
833
+ kernel_size=kernel_size,
834
+ stride=1,
835
+ dilation=dilation[1],
836
+ padding="same",
837
+ skip_transpose=True,
838
+ weight_norm=True,
839
+ ),
840
+ Conv1d(
841
+ in_channels=channels,
842
+ out_channels=channels,
843
+ kernel_size=kernel_size,
844
+ stride=1,
845
+ dilation=dilation[2],
846
+ padding="same",
847
+ skip_transpose=True,
848
+ weight_norm=True,
849
+ ),
850
+ ]
851
+ )
852
+
853
+ self.convs2 = nn.ModuleList(
854
+ [
855
+ Conv1d(
856
+ in_channels=channels,
857
+ out_channels=channels,
858
+ kernel_size=kernel_size,
859
+ stride=1,
860
+ dilation=1,
861
+ padding="same",
862
+ skip_transpose=True,
863
+ weight_norm=True,
864
+ ),
865
+ Conv1d(
866
+ in_channels=channels,
867
+ out_channels=channels,
868
+ kernel_size=kernel_size,
869
+ stride=1,
870
+ dilation=1,
871
+ padding="same",
872
+ skip_transpose=True,
873
+ weight_norm=True,
874
+ ),
875
+ Conv1d(
876
+ in_channels=channels,
877
+ out_channels=channels,
878
+ kernel_size=kernel_size,
879
+ stride=1,
880
+ dilation=1,
881
+ padding="same",
882
+ skip_transpose=True,
883
+ weight_norm=True,
884
+ ),
885
+ ]
886
+ )
887
+
888
+ def forward(self, x):
889
+ """Returns the output of ResBlock1
890
+
891
+ Arguments
892
+ ---------
893
+ x : torch.Tensor (batch, channel, time)
894
+ input tensor.
895
+
896
+ Returns
897
+ -------
898
+ The ResBlock outputs
899
+ """
900
+
901
+ for c1, c2 in zip(self.convs1, self.convs2):
902
+ xt = F.leaky_relu(x, LRELU_SLOPE)
903
+ xt = c1(xt)
904
+ xt = F.leaky_relu(xt, LRELU_SLOPE)
905
+ xt = c2(xt)
906
+ x = xt + x
907
+ return x
908
+
909
+ def remove_weight_norm(self):
910
+ """This functions removes weight normalization during inference."""
911
+ for layer in self.convs1:
912
+ layer.remove_weight_norm()
913
+ for layer in self.convs2:
914
+ layer.remove_weight_norm()
915
+
916
+
917
+ class ResBlock2(torch.nn.Module):
918
+ """
919
+ Residual Block Type 2, which has 2 convolutional layers in each convolution block.
920
+
921
+ Arguments
922
+ ---------
923
+ channels : int
924
+ number of hidden channels for the convolutional layers.
925
+ kernel_size : int
926
+ size of the convolution filter in each layer.
927
+ dilation : list
928
+ list of dilation value for each conv layer in a block.
929
+ """
930
+
931
+ def __init__(self, channels, kernel_size=3, dilation=(1, 3)):
932
+ super().__init__()
933
+ self.convs = nn.ModuleList(
934
+ [
935
+ Conv1d(
936
+ in_channels=channels,
937
+ out_channels=channels,
938
+ kernel_size=kernel_size,
939
+ stride=1,
940
+ dilation=dilation[0],
941
+ padding="same",
942
+ skip_transpose=True,
943
+ weight_norm=True,
944
+ ),
945
+ Conv1d(
946
+ in_channels=channels,
947
+ out_channels=channels,
948
+ kernel_size=kernel_size,
949
+ stride=1,
950
+ dilation=dilation[1],
951
+ padding="same",
952
+ skip_transpose=True,
953
+ weight_norm=True,
954
+ ),
955
+ ]
956
+ )
957
+
958
+ def forward(self, x):
959
+ """Returns the output of ResBlock1
960
+
961
+ Arguments
962
+ ---------
963
+ x : torch.Tensor (batch, channel, time)
964
+ input tensor.
965
+
966
+ Returns
967
+ -------
968
+ The ResBlock outputs
969
+ """
970
+
971
+ for c in self.convs:
972
+ xt = F.leaky_relu(x, LRELU_SLOPE)
973
+ xt = c(xt)
974
+ x = xt + x
975
+ return x
976
+
977
+ def remove_weight_norm(self):
978
+ """This functions removes weight normalization during inference."""
979
+ for layer in self.convs:
980
+ layer.remove_weight_norm()
981
+
982
+
983
+ class HiFiGANArabicGenerator(torch.nn.Module):
984
+ """HiFiGAN Generator with Multi-Receptive Field Fusion (MRF)
985
+
986
+ Arguments
987
+ ---------
988
+ in_channels : int
989
+ number of input tensor channels.
990
+ out_channels : int
991
+ number of output tensor channels.
992
+ resblock_type : str
993
+ type of the `ResBlock`. '1' or '2'.
994
+ resblock_dilation_sizes : List[List[int]]
995
+ list of dilation values in each layer of a `ResBlock`.
996
+ resblock_kernel_sizes : List[int]
997
+ list of kernel sizes for each `ResBlock`.
998
+ upsample_kernel_sizes : List[int]
999
+ list of kernel sizes for each transposed convolution.
1000
+ upsample_initial_channel : int
1001
+ number of channels for the first upsampling layer. This is divided by 2
1002
+ for each consecutive upsampling layer.
1003
+ upsample_factors : List[int]
1004
+ upsampling factors (stride) for each upsampling layer.
1005
+ inference_padding : int
1006
+ constant padding applied to the input at inference time. Defaults to 5.
1007
+ cond_channels : int
1008
+ If provided, adds a conv layer to the beginning of the forward.
1009
+ conv_post_bias : bool
1010
+ Whether to add a bias term to the final conv.
1011
+
1012
+ Example
1013
+ -------
1014
+ >>> inp_tensor = torch.rand([4, 80, 33])
1015
+ >>> hifigan_generator= HifiganGenerator(
1016
+ ... in_channels = 80,
1017
+ ... out_channels = 1,
1018
+ ... resblock_type = "1",
1019
+ ... resblock_dilation_sizes = [[1, 3, 5], [1, 3, 5], [1, 3, 5]],
1020
+ ... resblock_kernel_sizes = [3, 7, 11],
1021
+ ... upsample_kernel_sizes = [16, 16, 4, 4],
1022
+ ... upsample_initial_channel = 512,
1023
+ ... upsample_factors = [8, 8, 2, 2],
1024
+ ... )
1025
+ >>> out_tensor = hifigan_generator(inp_tensor)
1026
+ >>> out_tensor.shape
1027
+ torch.Size([4, 1, 8448])
1028
+ """
1029
+
1030
+ def __init__(
1031
+ self,
1032
+ in_channels,
1033
+ out_channels,
1034
+ resblock_type,
1035
+ resblock_dilation_sizes,
1036
+ resblock_kernel_sizes,
1037
+ upsample_kernel_sizes,
1038
+ upsample_initial_channel,
1039
+ upsample_factors,
1040
+ inference_padding=5,
1041
+ cond_channels=0,
1042
+ conv_post_bias=True,
1043
+ ):
1044
+ super().__init__()
1045
+ self.inference_padding = inference_padding
1046
+ self.num_kernels = len(resblock_kernel_sizes)
1047
+ self.num_upsamples = len(upsample_factors)
1048
+ # initial upsampling layers
1049
+ self.conv_pre = Conv1d(
1050
+ in_channels=in_channels,
1051
+ out_channels=upsample_initial_channel,
1052
+ kernel_size=7,
1053
+ stride=1,
1054
+ padding="same",
1055
+ skip_transpose=True,
1056
+ weight_norm=True,
1057
+ )
1058
+ resblock = ResBlock1 if resblock_type == "1" else ResBlock2
1059
+ # upsampling layers
1060
+ self.ups = nn.ModuleList()
1061
+ for i, (u, k) in enumerate(
1062
+ zip(upsample_factors, upsample_kernel_sizes)
1063
+ ):
1064
+ self.ups.append(
1065
+ ConvTranspose1d(
1066
+ in_channels=upsample_initial_channel // (2**i),
1067
+ out_channels=upsample_initial_channel // (2 ** (i + 1)),
1068
+ kernel_size=k,
1069
+ stride=u,
1070
+ padding=(k - u) // 2,
1071
+ skip_transpose=True,
1072
+ weight_norm=True,
1073
+ )
1074
+ )
1075
+ # MRF blocks
1076
+ self.resblocks = nn.ModuleList()
1077
+ for i in range(len(self.ups)):
1078
+ ch = upsample_initial_channel // (2 ** (i + 1))
1079
+ for _, (k, d) in enumerate(
1080
+ zip(resblock_kernel_sizes, resblock_dilation_sizes)
1081
+ ):
1082
+ self.resblocks.append(resblock(ch, k, d))
1083
+ # post convolution layer
1084
+ self.conv_post = Conv1d(
1085
+ in_channels=ch,
1086
+ out_channels=1,
1087
+ kernel_size=7,
1088
+ stride=1,
1089
+ padding="same",
1090
+ skip_transpose=True,
1091
+ bias=conv_post_bias,
1092
+ weight_norm=True,
1093
+ )
1094
+ if cond_channels > 0:
1095
+ self.cond_layer = Conv1d(
1096
+ in_channels=cond_channels,
1097
+ out_channels=upsample_initial_channel,
1098
+ kernel_size=1,
1099
+ )
1100
+
1101
+ def forward(self, x, g=None):
1102
+ """
1103
+ Arguments
1104
+ ---------
1105
+ x : torch.Tensor (batch, channel, time)
1106
+ feature input tensor.
1107
+ g : torch.Tensor (batch, 1, time)
1108
+ global conditioning input tensor.
1109
+
1110
+ Returns
1111
+ -------
1112
+ The generator outputs
1113
+ """
1114
+
1115
+ o = self.conv_pre(x)
1116
+ if hasattr(self, "cond_layer"):
1117
+ o = o + self.cond_layer(g)
1118
+ for i in range(self.num_upsamples):
1119
+ o = F.leaky_relu(o, LRELU_SLOPE)
1120
+ o = self.ups[i](o)
1121
+ z_sum = None
1122
+ for j in range(self.num_kernels):
1123
+ if z_sum is None:
1124
+ z_sum = self.resblocks[i * self.num_kernels + j](o)
1125
+ else:
1126
+ z_sum += self.resblocks[i * self.num_kernels + j](o)
1127
+ o = z_sum / self.num_kernels
1128
+ o = F.leaky_relu(o)
1129
+ o = self.conv_post(o)
1130
+ o = torch.tanh(o)
1131
+ return o
1132
+
1133
+ def remove_weight_norm(self):
1134
+ """This functions removes weight normalization during inference."""
1135
+
1136
+ for layer in self.ups:
1137
+ layer.remove_weight_norm()
1138
+ for layer in self.resblocks:
1139
+ layer.remove_weight_norm()
1140
+ self.conv_pre.remove_weight_norm()
1141
+ self.conv_post.remove_weight_norm()
1142
+
1143
+ @torch.no_grad()
1144
+ def inference(self, c, padding=True):
1145
+ """The inference function performs a padding and runs the forward method.
1146
+
1147
+ Arguments
1148
+ ---------
1149
+ c : torch.Tensor (batch, channel, time)
1150
+ feature input tensor.
1151
+ padding : bool
1152
+ Whether to pad tensor before forward.
1153
+
1154
+ Returns
1155
+ -------
1156
+ The generator outputs
1157
+ """
1158
+ if padding:
1159
+ c = torch.nn.functional.pad(
1160
+ c, (self.inference_padding, self.inference_padding), "replicate"
1161
+ )
1162
+ return self.forward(c)
1163
+
1164
+ @classmethod
1165
+ def from_pretrained(cls, checkpoint_path, config_path=None, device='cpu'):
1166
+ if config_path is None:
1167
+ config_path = os.path.join(os.path.dirname(__file__), "config.json")
1168
+ with open(config_path, "r") as file:
1169
+ config = json.load(file)
1170
+ model = cls(**config)
1171
+ ckpt = torch.load(checkpoint_path, map_location='cpu')
1172
+ model.load_state_dict(ckpt)
1173
+ return model.eval().to(device)
1174
+
1175
+
1176
+
1177
+ if __name__ == '__main__':
1178
+ gen = HifiganGenerator.from_pretrained("generator.ckpt", "config.json")
1179
+ x = torch.rand(1, 80, 122)
1180
+ mel = gen(x)