ORI-Muchim commited on
Commit
6f33d96
1 Parent(s): 1f3f80b

Update models.py

Browse files
Files changed (1) hide show
  1. models.py +963 -39
models.py CHANGED
@@ -1,3 +1,4 @@
 
1
  import math
2
  import torch
3
  from torch import nn
@@ -8,10 +9,16 @@ import modules
8
  import attentions
9
  import monotonic_align
10
 
11
- from torch.nn import Conv1d, ConvTranspose1d, Conv2d
12
  from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm
13
  from commons import init_weights, get_padding
14
 
 
 
 
 
 
 
15
 
16
  class StochasticDurationPredictor(nn.Module):
17
  def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, n_flows=4, gin_channels=0):
@@ -131,6 +138,148 @@ class DurationPredictor(nn.Module):
131
  return x * x_mask
132
 
133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
134
  class TextEncoder(nn.Module):
135
  def __init__(self,
136
  n_vocab,
@@ -140,7 +289,8 @@ class TextEncoder(nn.Module):
140
  n_heads,
141
  n_layers,
142
  kernel_size,
143
- p_dropout):
 
144
  super().__init__()
145
  self.n_vocab = n_vocab
146
  self.out_channels = out_channels
@@ -150,10 +300,9 @@ class TextEncoder(nn.Module):
150
  self.n_layers = n_layers
151
  self.kernel_size = kernel_size
152
  self.p_dropout = p_dropout
153
-
154
- if self.n_vocab != 0:
155
- self.emb = nn.Embedding(n_vocab, hidden_channels)
156
- nn.init.normal_(self.emb.weight, 0.0, hidden_channels ** -0.5)
157
 
158
  self.encoder = attentions.Encoder(
159
  hidden_channels,
@@ -161,22 +310,455 @@ class TextEncoder(nn.Module):
161
  n_heads,
162
  n_layers,
163
  kernel_size,
164
- p_dropout)
 
165
  self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
166
 
167
- def forward(self, x, x_lengths):
168
- if self.n_vocab != 0:
169
- x = self.emb(x) * math.sqrt(self.hidden_channels) # [b, t, h]
170
  x = torch.transpose(x, 1, -1) # [b, h, t]
171
  x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
172
 
173
- x = self.encoder(x * x_mask, x_mask)
174
  stats = self.proj(x) * x_mask
175
 
176
  m, logs = torch.split(stats, self.out_channels, dim=1)
177
  return x, m, logs, x_mask
178
 
179
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
180
  class ResidualCouplingBlock(nn.Module):
181
  def __init__(self,
182
  channels,
@@ -198,8 +780,16 @@ class ResidualCouplingBlock(nn.Module):
198
  self.flows = nn.ModuleList()
199
  for i in range(n_flows):
200
  self.flows.append(
201
- modules.ResidualCouplingLayer(channels, hidden_channels, kernel_size, dilation_rate, n_layers,
202
- gin_channels=gin_channels, mean_only=True))
 
 
 
 
 
 
 
 
203
  self.flows.append(modules.Flip())
204
 
205
  def forward(self, x, x_mask, g=None, reverse=False):
@@ -211,6 +801,11 @@ class ResidualCouplingBlock(nn.Module):
211
  x = flow(x, x_mask, g=g, reverse=reverse)
212
  return x
213
 
 
 
 
 
 
214
 
215
  class PosteriorEncoder(nn.Module):
216
  def __init__(self,
@@ -300,6 +895,272 @@ class Generator(torch.nn.Module):
300
  l.remove_weight_norm()
301
 
302
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
303
  class DiscriminatorP(torch.nn.Module):
304
  def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False):
305
  super(DiscriminatorP, self).__init__()
@@ -412,9 +1273,16 @@ class SynthesizerTrn(nn.Module):
412
  upsample_rates,
413
  upsample_initial_channel,
414
  upsample_kernel_sizes,
 
 
415
  n_speakers=0,
416
  gin_channels=0,
417
  use_sdp=True,
 
 
 
 
 
418
  **kwargs):
419
 
420
  super().__init__()
@@ -436,9 +1304,25 @@ class SynthesizerTrn(nn.Module):
436
  self.segment_size = segment_size
437
  self.n_speakers = n_speakers
438
  self.gin_channels = gin_channels
439
-
 
 
 
 
 
 
 
440
  self.use_sdp = use_sdp
441
-
 
 
 
 
 
 
 
 
 
442
  self.enc_p = TextEncoder(n_vocab,
443
  inter_channels,
444
  hidden_channels,
@@ -446,29 +1330,60 @@ class SynthesizerTrn(nn.Module):
446
  n_heads,
447
  n_layers,
448
  kernel_size,
449
- p_dropout)
450
- self.dec = Generator(inter_channels, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates,
451
- upsample_initial_channel, upsample_kernel_sizes, gin_channels=gin_channels)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
452
  self.enc_q = PosteriorEncoder(spec_channels, inter_channels, hidden_channels, 5, 1, 16,
453
  gin_channels=gin_channels)
454
- self.flow = ResidualCouplingBlock(inter_channels, hidden_channels, 5, 1, 4, gin_channels=gin_channels)
 
 
 
 
 
 
 
 
 
 
455
 
456
  if use_sdp:
457
  self.dp = StochasticDurationPredictor(hidden_channels, 192, 3, 0.5, 4, gin_channels=gin_channels)
458
  else:
459
  self.dp = DurationPredictor(hidden_channels, 256, 3, 0.5, gin_channels=gin_channels)
460
 
461
- if n_speakers > 1:
462
- self.emb_g = nn.Embedding(n_speakers, gin_channels)
463
 
464
  def forward(self, x, x_lengths, y, y_lengths, sid=None):
 
 
465
 
466
- x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths)
467
- if self.n_speakers > 1:
468
- g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
469
- else:
470
- g = None
471
-
472
  z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
473
  z_p = self.flow(z, y_mask, g=g)
474
 
@@ -482,6 +1397,10 @@ class SynthesizerTrn(nn.Module):
482
  neg_cent4 = torch.sum(-0.5 * (m_p ** 2) * s_p_sq_r, [1], keepdim=True) # [b, 1, t_s]
483
  neg_cent = neg_cent1 + neg_cent2 + neg_cent3 + neg_cent4
484
 
 
 
 
 
485
  attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)
486
  attn = monotonic_align.maximum_path(neg_cent, attn_mask.squeeze(1)).unsqueeze(1).detach()
487
 
@@ -489,6 +1408,8 @@ class SynthesizerTrn(nn.Module):
489
  if self.use_sdp:
490
  l_length = self.dp(x, x_mask, w, g=g)
491
  l_length = l_length / torch.sum(x_mask)
 
 
492
  else:
493
  logw_ = torch.log(w + 1e-6) * x_mask
494
  logw = self.dp(x, x_mask, g=g)
@@ -499,16 +1420,13 @@ class SynthesizerTrn(nn.Module):
499
  logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(1, 2)
500
 
501
  z_slice, ids_slice = commons.rand_slice_segments(z, y_lengths, self.segment_size)
502
- o = self.dec(z_slice, g=g)
503
- return o, l_length, attn, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q)
504
 
505
  def infer(self, x, x_lengths, sid=None, noise_scale=1, length_scale=1, noise_scale_w=1., max_len=None):
506
- x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths)
507
- if self.n_speakers > 1:
508
- g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
509
- else:
510
- g = None
511
 
 
512
  if self.use_sdp:
513
  logw = self.dp(x, x_mask, g=g, reverse=True, noise_scale=noise_scale_w)
514
  else:
@@ -526,15 +1444,21 @@ class SynthesizerTrn(nn.Module):
526
 
527
  z_p = m_p + torch.randn_like(m_p) * torch.exp(logs_p) * noise_scale
528
  z = self.flow(z_p, y_mask, g=g, reverse=True)
529
- o = self.dec((z * y_mask)[:, :, :max_len], g=g)
530
- return o, attn, y_mask, (z, z_p, m_p, logs_p)
531
 
 
 
 
 
 
 
 
532
  def voice_conversion(self, y, y_lengths, sid_src, sid_tgt):
533
- assert self.n_speakers > 1, "n_speakers have to be larger than 1."
534
  g_src = self.emb_g(sid_src).unsqueeze(-1)
535
  g_tgt = self.emb_g(sid_tgt).unsqueeze(-1)
536
  z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g_src)
537
  z_p = self.flow(z, y_mask, g=g_src)
538
  z_hat = self.flow(z_p, y_mask, g=g_tgt, reverse=True)
539
- o_hat = self.dec(z_hat * y_mask, g=g_tgt)
540
- return o_hat, y_mask, (z, z_p, z_hat)
 
 
1
+ import copy
2
  import math
3
  import torch
4
  from torch import nn
 
9
  import attentions
10
  import monotonic_align
11
 
12
+ from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
13
  from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm
14
  from commons import init_weights, get_padding
15
 
16
+ from pqmf import PQMF
17
+ from stft import TorchSTFT, OnnxSTFT
18
+
19
+ AVAILABLE_FLOW_TYPES = ["pre_conv", "pre_conv2", "fft", "mono_layer_inter_residual", "mono_layer_post_residual"]
20
+ AVAILABLE_DURATION_DISCRIMINATOR_TYPES = {"dur_disc_1": "DurationDiscriminator", "dur_disc_2": "DurationDiscriminator2"}
21
+
22
 
23
  class StochasticDurationPredictor(nn.Module):
24
  def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, n_flows=4, gin_channels=0):
 
138
  return x * x_mask
139
 
140
 
141
+ class DurationDiscriminator(nn.Module): # vits2
142
+ # TODO : not using "spk conditioning" for now according to the paper.
143
+ # Can be a better discriminator if we use it.
144
+ def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, gin_channels=0):
145
+ super().__init__()
146
+
147
+ self.in_channels = in_channels
148
+ self.filter_channels = filter_channels
149
+ self.kernel_size = kernel_size
150
+ self.p_dropout = p_dropout
151
+ self.gin_channels = gin_channels
152
+
153
+ self.drop = nn.Dropout(p_dropout)
154
+ self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size, padding=kernel_size // 2)
155
+ # self.norm_1 = modules.LayerNorm(filter_channels)
156
+ self.conv_2 = nn.Conv1d(filter_channels, filter_channels, kernel_size, padding=kernel_size // 2)
157
+ # self.norm_2 = modules.LayerNorm(filter_channels)
158
+ self.dur_proj = nn.Conv1d(1, filter_channels, 1)
159
+
160
+ self.pre_out_conv_1 = nn.Conv1d(2 * filter_channels, filter_channels, kernel_size, padding=kernel_size // 2)
161
+ self.pre_out_norm_1 = modules.LayerNorm(filter_channels)
162
+ self.pre_out_conv_2 = nn.Conv1d(filter_channels, filter_channels, kernel_size, padding=kernel_size // 2)
163
+ self.pre_out_norm_2 = modules.LayerNorm(filter_channels)
164
+
165
+ # if gin_channels != 0:
166
+ # self.cond = nn.Conv1d(gin_channels, in_channels, 1)
167
+
168
+ self.output_layer = nn.Sequential(
169
+ nn.Linear(filter_channels, 1),
170
+ nn.Sigmoid()
171
+ )
172
+
173
+ def forward_probability(self, x, x_mask, dur, g=None):
174
+ dur = self.dur_proj(dur)
175
+ x = torch.cat([x, dur], dim=1)
176
+ x = self.pre_out_conv_1(x * x_mask)
177
+ # x = torch.relu(x)
178
+ # x = self.pre_out_norm_1(x)
179
+ # x = self.drop(x)
180
+ x = self.pre_out_conv_2(x * x_mask)
181
+ # x = torch.relu(x)
182
+ # x = self.pre_out_norm_2(x)
183
+ # x = self.drop(x)
184
+ x = x * x_mask
185
+ x = x.transpose(1, 2)
186
+ output_prob = self.output_layer(x)
187
+ return output_prob
188
+
189
+ def forward(self, x, x_mask, dur_r, dur_hat, g=None):
190
+ x = torch.detach(x)
191
+ # if g is not None:
192
+ # g = torch.detach(g)
193
+ # x = x + self.cond(g)
194
+ x = self.conv_1(x * x_mask)
195
+ # x = torch.relu(x)
196
+ # x = self.norm_1(x)
197
+ # x = self.drop(x)
198
+ x = self.conv_2(x * x_mask)
199
+ # x = torch.relu(x)
200
+ # x = self.norm_2(x)
201
+ # x = self.drop(x)
202
+
203
+ output_probs = []
204
+ for dur in [dur_r, dur_hat]:
205
+ output_prob = self.forward_probability(x, x_mask, dur, g)
206
+ output_probs.append(output_prob)
207
+
208
+ return output_probs
209
+
210
+
211
+ class DurationDiscriminator2(nn.Module): # vits2 - DurationDiscriminator2
212
+ # TODO : not using "spk conditioning" for now according to the paper.
213
+ # Can be a better discriminator if we use it.
214
+ def __init__(
215
+ self, in_channels, filter_channels, kernel_size, p_dropout, gin_channels=0
216
+ ):
217
+ super().__init__()
218
+
219
+ self.in_channels = in_channels
220
+ self.filter_channels = filter_channels
221
+ self.kernel_size = kernel_size
222
+ self.p_dropout = p_dropout
223
+ self.gin_channels = gin_channels
224
+
225
+ self.conv_1 = nn.Conv1d(
226
+ in_channels, filter_channels, kernel_size, padding=kernel_size // 2
227
+ )
228
+ self.norm_1 = modules.LayerNorm(filter_channels)
229
+ self.conv_2 = nn.Conv1d(
230
+ filter_channels, filter_channels, kernel_size, padding=kernel_size // 2
231
+ )
232
+ self.norm_2 = modules.LayerNorm(filter_channels)
233
+ self.dur_proj = nn.Conv1d(1, filter_channels, 1)
234
+
235
+ self.pre_out_conv_1 = nn.Conv1d(
236
+ 2 * filter_channels, filter_channels, kernel_size, padding=kernel_size // 2
237
+ )
238
+ self.pre_out_norm_1 = modules.LayerNorm(filter_channels)
239
+ self.pre_out_conv_2 = nn.Conv1d(
240
+ filter_channels, filter_channels, kernel_size, padding=kernel_size // 2
241
+ )
242
+ self.pre_out_norm_2 = modules.LayerNorm(filter_channels)
243
+
244
+ # if gin_channels != 0:
245
+ # self.cond = nn.Conv1d(gin_channels, in_channels, 1)
246
+
247
+ self.output_layer = nn.Sequential(nn.Linear(filter_channels, 1), nn.Sigmoid())
248
+
249
+ def forward_probability(self, x, x_mask, dur, g=None):
250
+ dur = self.dur_proj(dur)
251
+ x = torch.cat([x, dur], dim=1)
252
+ x = self.pre_out_conv_1(x * x_mask)
253
+ x = torch.relu(x)
254
+ x = self.pre_out_norm_1(x)
255
+ x = self.pre_out_conv_2(x * x_mask)
256
+ x = torch.relu(x)
257
+ x = self.pre_out_norm_2(x)
258
+ x = x * x_mask
259
+ x = x.transpose(1, 2)
260
+ output_prob = self.output_layer(x)
261
+ return output_prob
262
+
263
+ def forward(self, x, x_mask, dur_r, dur_hat, g=None):
264
+ x = torch.detach(x)
265
+ # if g is not None:
266
+ # g = torch.detach(g)
267
+ # x = x + self.cond(g)
268
+ x = self.conv_1(x * x_mask)
269
+ x = torch.relu(x)
270
+ x = self.norm_1(x)
271
+ x = self.conv_2(x * x_mask)
272
+ x = torch.relu(x)
273
+ x = self.norm_2(x)
274
+
275
+ output_probs = []
276
+ for dur in [dur_r, dur_hat]:
277
+ output_prob = self.forward_probability(x, x_mask, dur, g)
278
+ output_probs.append([output_prob])
279
+
280
+ return output_probs
281
+
282
+
283
  class TextEncoder(nn.Module):
284
  def __init__(self,
285
  n_vocab,
 
289
  n_heads,
290
  n_layers,
291
  kernel_size,
292
+ p_dropout,
293
+ gin_channels=0):
294
  super().__init__()
295
  self.n_vocab = n_vocab
296
  self.out_channels = out_channels
 
300
  self.n_layers = n_layers
301
  self.kernel_size = kernel_size
302
  self.p_dropout = p_dropout
303
+ self.gin_channels = gin_channels
304
+ self.emb = nn.Embedding(n_vocab, hidden_channels)
305
+ nn.init.normal_(self.emb.weight, 0.0, hidden_channels ** -0.5)
 
306
 
307
  self.encoder = attentions.Encoder(
308
  hidden_channels,
 
310
  n_heads,
311
  n_layers,
312
  kernel_size,
313
+ p_dropout,
314
+ gin_channels=self.gin_channels)
315
  self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
316
 
317
+ def forward(self, x, x_lengths, g=None):
318
+ x = self.emb(x) * math.sqrt(self.hidden_channels) # [b, t, h]
 
319
  x = torch.transpose(x, 1, -1) # [b, h, t]
320
  x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
321
 
322
+ x = self.encoder(x * x_mask, x_mask, g=g)
323
  stats = self.proj(x) * x_mask
324
 
325
  m, logs = torch.split(stats, self.out_channels, dim=1)
326
  return x, m, logs, x_mask
327
 
328
 
329
+ class ResidualCouplingTransformersLayer2(nn.Module): # vits2
330
+ def __init__(
331
+ self,
332
+ channels,
333
+ hidden_channels,
334
+ kernel_size,
335
+ dilation_rate,
336
+ n_layers,
337
+ p_dropout=0,
338
+ gin_channels=0,
339
+ mean_only=False,
340
+ ):
341
+ assert channels % 2 == 0, "channels should be divisible by 2"
342
+ super().__init__()
343
+ self.channels = channels
344
+ self.hidden_channels = hidden_channels
345
+ self.kernel_size = kernel_size
346
+ self.dilation_rate = dilation_rate
347
+ self.n_layers = n_layers
348
+ self.half_channels = channels // 2
349
+ self.mean_only = mean_only
350
+
351
+ self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
352
+ self.pre_transformer = attentions.Encoder(
353
+ hidden_channels,
354
+ hidden_channels,
355
+ n_heads=2,
356
+ n_layers=1,
357
+ kernel_size=kernel_size,
358
+ p_dropout=p_dropout,
359
+ # window_size=None,
360
+ )
361
+ self.enc = modules.WN(
362
+ hidden_channels,
363
+ kernel_size,
364
+ dilation_rate,
365
+ n_layers,
366
+ p_dropout=p_dropout,
367
+ gin_channels=gin_channels,
368
+ )
369
+
370
+ self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
371
+ self.post.weight.data.zero_()
372
+ self.post.bias.data.zero_()
373
+
374
+ def forward(self, x, x_mask, g=None, reverse=False):
375
+ x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
376
+ h = self.pre(x0) * x_mask
377
+ h = h + self.pre_transformer(h * x_mask, x_mask) # vits2 residual connection
378
+ h = self.enc(h, x_mask, g=g)
379
+ stats = self.post(h) * x_mask
380
+ if not self.mean_only:
381
+ m, logs = torch.split(stats, [self.half_channels] * 2, 1)
382
+ else:
383
+ m = stats
384
+ logs = torch.zeros_like(m)
385
+ if not reverse:
386
+ x1 = m + x1 * torch.exp(logs) * x_mask
387
+ x = torch.cat([x0, x1], 1)
388
+ logdet = torch.sum(logs, [1, 2])
389
+ return x, logdet
390
+ else:
391
+ x1 = (x1 - m) * torch.exp(-logs) * x_mask
392
+ x = torch.cat([x0, x1], 1)
393
+ return x
394
+
395
+
396
+ class ResidualCouplingTransformersLayer(nn.Module): # vits2
397
+ def __init__(
398
+ self,
399
+ channels,
400
+ hidden_channels,
401
+ kernel_size,
402
+ dilation_rate,
403
+ n_layers,
404
+ p_dropout=0,
405
+ gin_channels=0,
406
+ mean_only=False,
407
+ ):
408
+ assert channels % 2 == 0, "channels should be divisible by 2"
409
+ super().__init__()
410
+ self.channels = channels
411
+ self.hidden_channels = hidden_channels
412
+ self.kernel_size = kernel_size
413
+ self.dilation_rate = dilation_rate
414
+ self.n_layers = n_layers
415
+ self.half_channels = channels // 2
416
+ self.mean_only = mean_only
417
+ # vits2
418
+ self.pre_transformer = attentions.Encoder(
419
+ self.half_channels,
420
+ self.half_channels,
421
+ n_heads=2,
422
+ n_layers=2,
423
+ kernel_size=3,
424
+ p_dropout=0.1,
425
+ window_size=None
426
+ )
427
+
428
+ self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
429
+ self.enc = modules.WN(
430
+ hidden_channels,
431
+ kernel_size,
432
+ dilation_rate,
433
+ n_layers,
434
+ p_dropout=p_dropout,
435
+ gin_channels=gin_channels,
436
+ )
437
+ # vits2
438
+ self.post_transformer = attentions.Encoder(
439
+ self.hidden_channels,
440
+ self.hidden_channels,
441
+ n_heads=2,
442
+ n_layers=2,
443
+ kernel_size=3,
444
+ p_dropout=0.1,
445
+ window_size=None
446
+ )
447
+
448
+ self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
449
+ self.post.weight.data.zero_()
450
+ self.post.bias.data.zero_()
451
+
452
+ def forward(self, x, x_mask, g=None, reverse=False):
453
+ x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
454
+ x0_ = self.pre_transformer(x0 * x_mask, x_mask) # vits2
455
+ x0_ = x0_ + x0 # vits2 residual connection
456
+ h = self.pre(x0_) * x_mask # changed from x0 to x0_ to retain x0 for the flow
457
+ h = self.enc(h, x_mask, g=g)
458
+
459
+ # vits2 - (experimental;uncomment the following 2 line to use)
460
+ # h_ = self.post_transformer(h, x_mask)
461
+ # h = h + h_ #vits2 residual connection
462
+
463
+ stats = self.post(h) * x_mask
464
+ if not self.mean_only:
465
+ m, logs = torch.split(stats, [self.half_channels] * 2, 1)
466
+ else:
467
+ m = stats
468
+ logs = torch.zeros_like(m)
469
+ if not reverse:
470
+ x1 = m + x1 * torch.exp(logs) * x_mask
471
+ x = torch.cat([x0, x1], 1)
472
+ logdet = torch.sum(logs, [1, 2])
473
+ return x, logdet
474
+ else:
475
+ x1 = (x1 - m) * torch.exp(-logs) * x_mask
476
+ x = torch.cat([x0, x1], 1)
477
+ return x
478
+
479
+ def remove_weight_norm(self): # !
480
+ self.enc.remove_weight_norm()
481
+
482
+
483
+ class FFTransformerCouplingLayer(nn.Module): # vits2
484
+ def __init__(self,
485
+ channels,
486
+ hidden_channels,
487
+ kernel_size,
488
+ n_layers,
489
+ n_heads,
490
+ p_dropout=0,
491
+ filter_channels=768,
492
+ mean_only=False,
493
+ gin_channels=0
494
+ ):
495
+ assert channels % 2 == 0, "channels should be divisible by 2"
496
+ super().__init__()
497
+ self.channels = channels
498
+ self.hidden_channels = hidden_channels
499
+ self.kernel_size = kernel_size
500
+ self.n_layers = n_layers
501
+ self.half_channels = channels // 2
502
+ self.mean_only = mean_only
503
+
504
+ self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
505
+ self.enc = attentions.FFT(
506
+ hidden_channels,
507
+ filter_channels,
508
+ n_heads,
509
+ n_layers,
510
+ kernel_size,
511
+ p_dropout,
512
+ isflow=True,
513
+ gin_channels=gin_channels
514
+ )
515
+ self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
516
+ self.post.weight.data.zero_()
517
+ self.post.bias.data.zero_()
518
+
519
+ def forward(self, x, x_mask, g=None, reverse=False):
520
+ x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
521
+ h = self.pre(x0) * x_mask
522
+ h_ = self.enc(h, x_mask, g=g)
523
+ h = h_ + h
524
+ stats = self.post(h) * x_mask
525
+ if not self.mean_only:
526
+ m, logs = torch.split(stats, [self.half_channels] * 2, 1)
527
+ else:
528
+ m = stats
529
+ logs = torch.zeros_like(m)
530
+
531
+ if not reverse:
532
+ x1 = m + x1 * torch.exp(logs) * x_mask
533
+ x = torch.cat([x0, x1], 1)
534
+ logdet = torch.sum(logs, [1, 2])
535
+ return x, logdet
536
+ else:
537
+ x1 = (x1 - m) * torch.exp(-logs) * x_mask
538
+ x = torch.cat([x0, x1], 1)
539
+ return x
540
+
541
+
542
+ class MonoTransformerFlowLayer(nn.Module): # vits2
543
+ def __init__(
544
+ self,
545
+ channels,
546
+ hidden_channels,
547
+ mean_only=False,
548
+ residual_connection=False,
549
+ # according to VITS-2 paper fig 1B set residual_connection=True
550
+ ):
551
+ assert channels % 2 == 0, "channels should be divisible by 2"
552
+ super().__init__()
553
+ self.channels = channels
554
+ self.hidden_channels = hidden_channels
555
+ self.half_channels = channels // 2
556
+ self.mean_only = mean_only
557
+ self.residual_connection = residual_connection
558
+ # vits2
559
+ self.pre_transformer = attentions.Encoder(
560
+ self.half_channels,
561
+ self.half_channels,
562
+ n_heads=2,
563
+ n_layers=2,
564
+ kernel_size=3,
565
+ p_dropout=0.1,
566
+ window_size=None
567
+ )
568
+
569
+ self.post = nn.Conv1d(self.half_channels, self.half_channels * (2 - mean_only), 1)
570
+ self.post.weight.data.zero_()
571
+ self.post.bias.data.zero_()
572
+
573
+ def forward(self, x, x_mask, g=None, reverse=False):
574
+ if self.residual_connection:
575
+ if not reverse:
576
+ x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
577
+ x0_ = x0 * x_mask
578
+ x0_ = self.pre_transformer(x0, x_mask) # vits2
579
+ stats = self.post(x0_) * x_mask
580
+ if not self.mean_only:
581
+ m, logs = torch.split(stats, [self.half_channels] * 2, 1)
582
+ else:
583
+ m = stats
584
+ logs = torch.zeros_like(m)
585
+ x1 = m + x1 * torch.exp(logs) * x_mask
586
+ x_ = torch.cat([x0, x1], 1)
587
+ x = x + x_
588
+ logdet = torch.sum(torch.log(torch.exp(logs) + 1), [1, 2])
589
+ logdet = logdet + torch.log(torch.tensor(2)) * (x0.shape[1] * x0.shape[2])
590
+ return x, logdet
591
+
592
+ else:
593
+ x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
594
+ x0 = x0 / 2
595
+ x0_ = x0 * x_mask
596
+ x0_ = self.pre_transformer(x0, x_mask) # vits2
597
+ stats = self.post(x0_) * x_mask
598
+ if not self.mean_only:
599
+ m, logs = torch.split(stats, [self.half_channels] * 2, 1)
600
+ else:
601
+ m = stats
602
+ logs = torch.zeros_like(m)
603
+ x1_ = ((x1 - m) / (1 + torch.exp(-logs))) * x_mask
604
+ x = torch.cat([x0, x1_], 1)
605
+ return x
606
+ else:
607
+ x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
608
+ x0_ = self.pre_transformer(x0 * x_mask, x_mask) # vits2
609
+ h = x0_ + x0 # vits2
610
+ stats = self.post(h) * x_mask
611
+ if not self.mean_only:
612
+ m, logs = torch.split(stats, [self.half_channels] * 2, 1)
613
+ else:
614
+ m = stats
615
+ logs = torch.zeros_like(m)
616
+ if not reverse:
617
+ x1 = m + x1 * torch.exp(logs) * x_mask
618
+ x = torch.cat([x0, x1], 1)
619
+ logdet = torch.sum(logs, [1, 2])
620
+ return x, logdet
621
+ else:
622
+ x1 = (x1 - m) * torch.exp(-logs) * x_mask
623
+ x = torch.cat([x0, x1], 1)
624
+ return x
625
+
626
+
627
+ class ResidualCouplingTransformersBlock(nn.Module): # vits2
628
+ def __init__(self,
629
+ channels,
630
+ hidden_channels,
631
+ kernel_size,
632
+ dilation_rate,
633
+ n_layers,
634
+ n_flows=4,
635
+ gin_channels=0,
636
+ use_transformer_flows=False,
637
+ transformer_flow_type="pre_conv",
638
+ ):
639
+ super().__init__()
640
+ self.channels = channels
641
+ self.hidden_channels = hidden_channels
642
+ self.kernel_size = kernel_size
643
+ self.dilation_rate = dilation_rate
644
+ self.n_layers = n_layers
645
+ self.n_flows = n_flows
646
+ self.gin_channels = gin_channels
647
+
648
+ self.flows = nn.ModuleList()
649
+ # TODO : clean up this mess
650
+ if use_transformer_flows:
651
+ if transformer_flow_type == "pre_conv":
652
+ for i in range(n_flows):
653
+ self.flows.append(
654
+ ResidualCouplingTransformersLayer(
655
+ channels,
656
+ hidden_channels,
657
+ kernel_size,
658
+ dilation_rate,
659
+ n_layers,
660
+ gin_channels=gin_channels,
661
+ mean_only=True
662
+ )
663
+ )
664
+ self.flows.append(modules.Flip())
665
+ elif transformer_flow_type == "pre_conv2":
666
+ for i in range(n_flows):
667
+ self.flows.append(
668
+ ResidualCouplingTransformersLayer2(
669
+ channels,
670
+ hidden_channels,
671
+ kernel_size,
672
+ dilation_rate,
673
+ n_layers,
674
+ gin_channels=gin_channels,
675
+ mean_only=True,
676
+ )
677
+ )
678
+ self.flows.append(modules.Flip())
679
+ elif transformer_flow_type == "fft":
680
+ for i in range(n_flows):
681
+ self.flows.append(
682
+ FFTransformerCouplingLayer(
683
+ channels,
684
+ hidden_channels,
685
+ kernel_size,
686
+ dilation_rate,
687
+ n_layers,
688
+ gin_channels=gin_channels,
689
+ mean_only=True
690
+ )
691
+ )
692
+ self.flows.append(modules.Flip())
693
+ elif transformer_flow_type == "mono_layer_inter_residual":
694
+ for i in range(n_flows):
695
+ self.flows.append(
696
+ modules.ResidualCouplingLayer(
697
+ channels,
698
+ hidden_channels,
699
+ kernel_size,
700
+ dilation_rate,
701
+ n_layers,
702
+ gin_channels=gin_channels,
703
+ mean_only=True
704
+ )
705
+ )
706
+ self.flows.append(modules.Flip())
707
+ self.flows.append(
708
+ MonoTransformerFlowLayer(
709
+ channels, hidden_channels, mean_only=True
710
+ )
711
+ )
712
+ elif transformer_flow_type == "mono_layer_post_residual":
713
+ for i in range(n_flows):
714
+ self.flows.append(
715
+ modules.ResidualCouplingLayer(
716
+ channels,
717
+ hidden_channels,
718
+ kernel_size,
719
+ dilation_rate,
720
+ n_layers,
721
+ gin_channels=gin_channels,
722
+ mean_only=True,
723
+ )
724
+ )
725
+ self.flows.append(modules.Flip())
726
+ self.flows.append(
727
+ MonoTransformerFlowLayer(
728
+ channels, hidden_channels, mean_only=True,
729
+ residual_connection=True
730
+ )
731
+ )
732
+ else:
733
+ for i in range(n_flows):
734
+ self.flows.append(
735
+ modules.ResidualCouplingLayer(
736
+ channels,
737
+ hidden_channels,
738
+ kernel_size,
739
+ dilation_rate,
740
+ n_layers,
741
+ gin_channels=gin_channels,
742
+ mean_only=True
743
+ )
744
+ )
745
+ self.flows.append(modules.Flip())
746
+
747
+ def forward(self, x, x_mask, g=None, reverse=False):
748
+ if not reverse:
749
+ for flow in self.flows:
750
+ x, _ = flow(x, x_mask, g=g, reverse=reverse)
751
+ else:
752
+ for flow in reversed(self.flows):
753
+ x = flow(x, x_mask, g=g, reverse=reverse)
754
+ return x
755
+
756
+ def remove_weight_norm(self): # !
757
+ for i, l in enumerate(self.flows):
758
+ if i % 2 == 0:
759
+ l.remove_weight_norm()
760
+
761
+
762
  class ResidualCouplingBlock(nn.Module):
763
  def __init__(self,
764
  channels,
 
780
  self.flows = nn.ModuleList()
781
  for i in range(n_flows):
782
  self.flows.append(
783
+ modules.ResidualCouplingLayer(
784
+ channels,
785
+ hidden_channels,
786
+ kernel_size,
787
+ dilation_rate,
788
+ n_layers,
789
+ gin_channels=gin_channels,
790
+ mean_only=True
791
+ )
792
+ )
793
  self.flows.append(modules.Flip())
794
 
795
  def forward(self, x, x_mask, g=None, reverse=False):
 
801
  x = flow(x, x_mask, g=g, reverse=reverse)
802
  return x
803
 
804
+ def remove_weight_norm(self): # !
805
+ for i, l in enumerate(self.flows):
806
+ if i % 2 == 0:
807
+ l.remove_weight_norm()
808
+
809
 
810
  class PosteriorEncoder(nn.Module):
811
  def __init__(self,
 
895
  l.remove_weight_norm()
896
 
897
 
898
+ class iSTFT_Generator(torch.nn.Module):
899
+ def __init__(self, initial_channel, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates,
900
+ upsample_initial_channel, upsample_kernel_sizes, gen_istft_n_fft, gen_istft_hop_size,
901
+ gin_channels=0, is_onnx=False):
902
+ super(iSTFT_Generator, self).__init__()
903
+ # self.h = h
904
+ self.gen_istft_n_fft = gen_istft_n_fft
905
+ self.gen_istft_hop_size = gen_istft_hop_size
906
+
907
+ self.num_kernels = len(resblock_kernel_sizes)
908
+ self.num_upsamples = len(upsample_rates)
909
+ self.conv_pre = weight_norm(Conv1d(initial_channel, upsample_initial_channel, 7, 1, padding=3))
910
+ resblock = modules.ResBlock1 if resblock == '1' else modules.ResBlock2
911
+
912
+ self.ups = nn.ModuleList()
913
+ for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
914
+ self.ups.append(weight_norm(
915
+ ConvTranspose1d(upsample_initial_channel // (2 ** i), upsample_initial_channel // (2 ** (i + 1)),
916
+ k, u, padding=(k - u) // 2)))
917
+
918
+ self.resblocks = nn.ModuleList()
919
+ for i in range(len(self.ups)):
920
+ ch = upsample_initial_channel // (2 ** (i + 1))
921
+ for j, (k, d) in enumerate(zip(resblock_kernel_sizes, resblock_dilation_sizes)):
922
+ self.resblocks.append(resblock(ch, k, d))
923
+
924
+ self.post_n_fft = self.gen_istft_n_fft
925
+ self.conv_post = weight_norm(Conv1d(ch, self.post_n_fft + 2, 7, 1, padding=3))
926
+ self.ups.apply(init_weights)
927
+ self.conv_post.apply(init_weights)
928
+ self.reflection_pad = torch.nn.ReflectionPad1d((1, 0))
929
+ '''
930
+ self.stft = TorchSTFT(filter_length=self.gen_istft_n_fft, hop_length=self.gen_istft_hop_size,
931
+ win_length=self.gen_istft_n_fft)
932
+ '''
933
+ # - for onnx
934
+ if is_onnx == True:
935
+ self.stft = OnnxSTFT(filter_length=self.gen_istft_n_fft, hop_length=self.gen_istft_hop_size,
936
+ win_length=self.gen_istft_n_fft)
937
+ else:
938
+ self.stft = TorchSTFT(filter_length=self.gen_istft_n_fft, hop_length=self.gen_istft_hop_size,
939
+ win_length=self.gen_istft_n_fft)
940
+
941
+ def forward(self, x, g=None):
942
+ x = self.conv_pre(x)
943
+ for i in range(self.num_upsamples):
944
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
945
+ x = self.ups[i](x)
946
+ xs = None
947
+ for j in range(self.num_kernels):
948
+ if xs is None:
949
+ xs = self.resblocks[i * self.num_kernels + j](x)
950
+ else:
951
+ xs += self.resblocks[i * self.num_kernels + j](x)
952
+ x = xs / self.num_kernels
953
+ x = F.leaky_relu(x)
954
+ x = self.reflection_pad(x)
955
+ x = self.conv_post(x)
956
+ spec = torch.exp(x[:, :self.post_n_fft // 2 + 1, :])
957
+ phase = math.pi * torch.sin(x[:, self.post_n_fft // 2 + 1:, :])
958
+ out = self.stft.inverse(spec, phase).to(x.device)
959
+ return out, None
960
+
961
+ def remove_weight_norm(self):
962
+ print('Removing weight norm...')
963
+ for l in self.ups:
964
+ remove_weight_norm(l)
965
+ for l in self.resblocks:
966
+ l.remove_weight_norm()
967
+ remove_weight_norm(self.conv_pre)
968
+ remove_weight_norm(self.conv_post)
969
+
970
+
971
+ class Multiband_iSTFT_Generator(torch.nn.Module): # !
972
+ def __init__(self, initial_channel, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates,
973
+ upsample_initial_channel, upsample_kernel_sizes, gen_istft_n_fft, gen_istft_hop_size, subbands,
974
+ gin_channels=0, is_onnx=False):
975
+ super(Multiband_iSTFT_Generator, self).__init__()
976
+ # self.h = h
977
+ self.subbands = subbands
978
+ self.num_kernels = len(resblock_kernel_sizes)
979
+ self.num_upsamples = len(upsample_rates)
980
+ self.conv_pre = weight_norm(Conv1d(initial_channel, upsample_initial_channel, 7, 1, padding=3))
981
+ resblock = modules.ResBlock1 if resblock == '1' else modules.ResBlock2
982
+
983
+ self.ups = nn.ModuleList()
984
+ for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
985
+ self.ups.append(weight_norm(
986
+ ConvTranspose1d(upsample_initial_channel // (2 ** i), upsample_initial_channel // (2 ** (i + 1)),
987
+ k, u, padding=(k - u) // 2)))
988
+
989
+ self.resblocks = nn.ModuleList()
990
+ for i in range(len(self.ups)):
991
+ ch = upsample_initial_channel // (2 ** (i + 1))
992
+ for j, (k, d) in enumerate(zip(resblock_kernel_sizes, resblock_dilation_sizes)):
993
+ self.resblocks.append(resblock(ch, k, d))
994
+
995
+ self.post_n_fft = gen_istft_n_fft
996
+ self.ups.apply(init_weights)
997
+ self.reflection_pad = torch.nn.ReflectionPad1d((1, 0))
998
+ self.reshape_pixelshuffle = []
999
+
1000
+ self.subband_conv_post = weight_norm(Conv1d(ch, self.subbands * (self.post_n_fft + 2), 7, 1, padding=3))
1001
+
1002
+ self.subband_conv_post.apply(init_weights)
1003
+
1004
+ self.gen_istft_n_fft = gen_istft_n_fft
1005
+ self.gen_istft_hop_size = gen_istft_hop_size
1006
+
1007
+ #- for onnx
1008
+ if is_onnx == True:
1009
+ self.stft = OnnxSTFT(filter_length=self.gen_istft_n_fft, hop_length=self.gen_istft_hop_size, win_length=self.gen_istft_n_fft)
1010
+ else:
1011
+ self.stft = TorchSTFT(filter_length=self.gen_istft_n_fft, hop_length=self.gen_istft_hop_size, win_length=self.gen_istft_n_fft)
1012
+
1013
+ def forward(self, x, g=None):
1014
+ '''
1015
+ stft = TorchSTFT(filter_length=self.gen_istft_n_fft, hop_length=self.gen_istft_hop_size,
1016
+ win_length=self.gen_istft_n_fft).to(x.device) # !
1017
+ '''
1018
+ stft = self.stft.to(x.device)
1019
+ pqmf = PQMF(x.device)
1020
+
1021
+ x = self.conv_pre(x) # [B, ch, length]
1022
+
1023
+ for i in range(self.num_upsamples):
1024
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
1025
+ x = self.ups[i](x)
1026
+
1027
+ xs = None
1028
+ for j in range(self.num_kernels):
1029
+ if xs is None:
1030
+ xs = self.resblocks[i * self.num_kernels + j](x)
1031
+ else:
1032
+ xs += self.resblocks[i * self.num_kernels + j](x)
1033
+ x = xs / self.num_kernels
1034
+
1035
+ x = F.leaky_relu(x)
1036
+ x = self.reflection_pad(x)
1037
+ x = self.subband_conv_post(x)
1038
+ x = torch.reshape(x, (x.shape[0], self.subbands, x.shape[1] // self.subbands, x.shape[-1]))
1039
+
1040
+ spec = torch.exp(x[:, :, :self.post_n_fft // 2 + 1, :])
1041
+ phase = math.pi * torch.sin(x[:, :, self.post_n_fft // 2 + 1:, :])
1042
+
1043
+ y_mb_hat = stft.inverse(
1044
+ torch.reshape(spec, (spec.shape[0] * self.subbands, self.gen_istft_n_fft // 2 + 1, spec.shape[-1])),
1045
+ torch.reshape(phase, (phase.shape[0] * self.subbands, self.gen_istft_n_fft // 2 + 1, phase.shape[-1])))
1046
+ y_mb_hat = torch.reshape(y_mb_hat, (x.shape[0], self.subbands, 1, y_mb_hat.shape[-1]))
1047
+ y_mb_hat = y_mb_hat.squeeze(-2)
1048
+
1049
+ y_g_hat = pqmf.synthesis(y_mb_hat)
1050
+
1051
+ return y_g_hat, y_mb_hat
1052
+
1053
+ def remove_weight_norm(self):
1054
+ print('Removing weight norm...')
1055
+ for l in self.ups:
1056
+ remove_weight_norm(l)
1057
+ for l in self.resblocks:
1058
+ l.remove_weight_norm()
1059
+
1060
+
1061
+ class Multistream_iSTFT_Generator(torch.nn.Module):
1062
+ def __init__(self, initial_channel, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates,
1063
+ upsample_initial_channel, upsample_kernel_sizes, gen_istft_n_fft, gen_istft_hop_size, subbands,
1064
+ gin_channels=0, is_onnx=False):
1065
+ super(Multistream_iSTFT_Generator, self).__init__()
1066
+ # self.h = h
1067
+ self.subbands = subbands
1068
+ self.num_kernels = len(resblock_kernel_sizes)
1069
+ self.num_upsamples = len(upsample_rates)
1070
+ self.conv_pre = weight_norm(Conv1d(initial_channel, upsample_initial_channel, 7, 1, padding=3))
1071
+ resblock = modules.ResBlock1 if resblock == '1' else modules.ResBlock2
1072
+
1073
+ self.ups = nn.ModuleList()
1074
+ for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
1075
+ self.ups.append(weight_norm(
1076
+ ConvTranspose1d(upsample_initial_channel // (2 ** i), upsample_initial_channel // (2 ** (i + 1)),
1077
+ k, u, padding=(k - u) // 2)))
1078
+
1079
+ self.resblocks = nn.ModuleList()
1080
+ for i in range(len(self.ups)):
1081
+ ch = upsample_initial_channel // (2 ** (i + 1))
1082
+ for j, (k, d) in enumerate(zip(resblock_kernel_sizes, resblock_dilation_sizes)):
1083
+ self.resblocks.append(resblock(ch, k, d))
1084
+
1085
+ self.post_n_fft = gen_istft_n_fft
1086
+ self.ups.apply(init_weights)
1087
+ self.reflection_pad = torch.nn.ReflectionPad1d((1, 0))
1088
+ self.reshape_pixelshuffle = []
1089
+
1090
+ self.subband_conv_post = weight_norm(Conv1d(ch, self.subbands * (self.post_n_fft + 2), 7, 1, padding=3))
1091
+
1092
+ self.subband_conv_post.apply(init_weights)
1093
+
1094
+ self.gen_istft_n_fft = gen_istft_n_fft
1095
+ self.gen_istft_hop_size = gen_istft_hop_size
1096
+
1097
+ updown_filter = torch.zeros((self.subbands, self.subbands, self.subbands)).float()
1098
+ for k in range(self.subbands):
1099
+ updown_filter[k, k, 0] = 1.0
1100
+ self.register_buffer("updown_filter", updown_filter)
1101
+ #self.multistream_conv_post = weight_norm(Conv1d(4, 1, kernel_size=63, bias=False, padding=get_padding(63, 1)))
1102
+ self.multistream_conv_post = weight_norm(Conv1d(self.subbands, 1, kernel_size=63, bias=False, padding=get_padding(63, 1))) # from MB-iSTFT-VITS-44100-Ja
1103
+ self.multistream_conv_post.apply(init_weights)
1104
+
1105
+ #- for onnx
1106
+ if is_onnx == True:
1107
+ self.stft = OnnxSTFT(filter_length=self.gen_istft_n_fft, hop_length=self.gen_istft_hop_size, win_length=self.gen_istft_n_fft)
1108
+ else:
1109
+ self.stft = TorchSTFT(filter_length=self.gen_istft_n_fft, hop_length=self.gen_istft_hop_size, win_length=self.gen_istft_n_fft)
1110
+
1111
+ def forward(self, x, g=None):
1112
+ '''
1113
+ stft = TorchSTFT(filter_length=self.gen_istft_n_fft, hop_length=self.gen_istft_hop_size,
1114
+ win_length=self.gen_istft_n_fft).to(x.device) # !
1115
+ '''
1116
+ stft = self.stft.to(x.device)
1117
+
1118
+ # pqmf = PQMF(x.device)
1119
+
1120
+ x = self.conv_pre(x) # [B, ch, length]
1121
+
1122
+ for i in range(self.num_upsamples):
1123
+
1124
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
1125
+ x = self.ups[i](x)
1126
+
1127
+ xs = None
1128
+ for j in range(self.num_kernels):
1129
+ if xs is None:
1130
+ xs = self.resblocks[i * self.num_kernels + j](x)
1131
+ else:
1132
+ xs += self.resblocks[i * self.num_kernels + j](x)
1133
+ x = xs / self.num_kernels
1134
+
1135
+ x = F.leaky_relu(x)
1136
+ x = self.reflection_pad(x)
1137
+ x = self.subband_conv_post(x)
1138
+ x = torch.reshape(x, (x.shape[0], self.subbands, x.shape[1] // self.subbands, x.shape[-1]))
1139
+
1140
+ spec = torch.exp(x[:, :, :self.post_n_fft // 2 + 1, :])
1141
+ phase = math.pi * torch.sin(x[:, :, self.post_n_fft // 2 + 1:, :])
1142
+
1143
+ y_mb_hat = stft.inverse(
1144
+ torch.reshape(spec, (spec.shape[0] * self.subbands, self.gen_istft_n_fft // 2 + 1, spec.shape[-1])),
1145
+ torch.reshape(phase, (phase.shape[0] * self.subbands, self.gen_istft_n_fft // 2 + 1, phase.shape[-1])))
1146
+ y_mb_hat = torch.reshape(y_mb_hat, (x.shape[0], self.subbands, 1, y_mb_hat.shape[-1]))
1147
+ y_mb_hat = y_mb_hat.squeeze(-2)
1148
+
1149
+ #y_mb_hat = F.conv_transpose1d(y_mb_hat, self.updown_filter.cuda(x.device) * self.subbands, stride=self.subbands)
1150
+ y_mb_hat = F.conv_transpose1d(y_mb_hat, self.updown_filter.to(x.device) * self.subbands, stride=self.subbands)
1151
+
1152
+ y_g_hat = self.multistream_conv_post(y_mb_hat)
1153
+
1154
+ return y_g_hat, y_mb_hat
1155
+
1156
+ def remove_weight_norm(self):
1157
+ print('Removing weight norm...')
1158
+ for l in self.ups:
1159
+ remove_weight_norm(l)
1160
+ for l in self.resblocks:
1161
+ l.remove_weight_norm()
1162
+
1163
+
1164
  class DiscriminatorP(torch.nn.Module):
1165
  def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False):
1166
  super(DiscriminatorP, self).__init__()
 
1273
  upsample_rates,
1274
  upsample_initial_channel,
1275
  upsample_kernel_sizes,
1276
+ gen_istft_n_fft,
1277
+ gen_istft_hop_size,
1278
  n_speakers=0,
1279
  gin_channels=0,
1280
  use_sdp=True,
1281
+ ms_istft_vits=False,
1282
+ mb_istft_vits=False,
1283
+ subbands=False,
1284
+ istft_vits=False,
1285
+ is_onnx=False,
1286
  **kwargs):
1287
 
1288
  super().__init__()
 
1304
  self.segment_size = segment_size
1305
  self.n_speakers = n_speakers
1306
  self.gin_channels = gin_channels
1307
+ self.ms_istft_vits = ms_istft_vits
1308
+ self.mb_istft_vits = mb_istft_vits
1309
+ self.istft_vits = istft_vits
1310
+ self.use_spk_conditioned_encoder = kwargs.get("use_spk_conditioned_encoder", False)
1311
+ self.use_transformer_flows = kwargs.get("use_transformer_flows", False)
1312
+ self.transformer_flow_type = kwargs.get("transformer_flow_type", "mono_layer_post_residual")
1313
+ if self.use_transformer_flows:
1314
+ assert self.transformer_flow_type in AVAILABLE_FLOW_TYPES, f"transformer_flow_type must be one of {AVAILABLE_FLOW_TYPES}"
1315
  self.use_sdp = use_sdp
1316
+ # self.use_duration_discriminator = kwargs.get("use_duration_discriminator", False)
1317
+ self.use_noise_scaled_mas = kwargs.get("use_noise_scaled_mas", False)
1318
+ self.mas_noise_scale_initial = kwargs.get("mas_noise_scale_initial", 0.01)
1319
+ self.noise_scale_delta = kwargs.get("noise_scale_delta", 2e-6)
1320
+
1321
+ self.current_mas_noise_scale = self.mas_noise_scale_initial
1322
+ if self.use_spk_conditioned_encoder and gin_channels > 0:
1323
+ self.enc_gin_channels = gin_channels
1324
+ else:
1325
+ self.enc_gin_channels = 0
1326
  self.enc_p = TextEncoder(n_vocab,
1327
  inter_channels,
1328
  hidden_channels,
 
1330
  n_heads,
1331
  n_layers,
1332
  kernel_size,
1333
+ p_dropout,
1334
+ gin_channels=self.enc_gin_channels)
1335
+
1336
+ if mb_istft_vits == True:
1337
+ print('Multi-band iSTFT VITS2')
1338
+ self.dec = Multiband_iSTFT_Generator(inter_channels, resblock, resblock_kernel_sizes,
1339
+ resblock_dilation_sizes,
1340
+ upsample_rates, upsample_initial_channel, upsample_kernel_sizes,
1341
+ gen_istft_n_fft, gen_istft_hop_size, subbands,
1342
+ gin_channels=gin_channels, is_onnx=is_onnx)
1343
+ elif ms_istft_vits == True:
1344
+ print('Multi-stream iSTFT VITS2')
1345
+ self.dec = Multistream_iSTFT_Generator(inter_channels, resblock, resblock_kernel_sizes,
1346
+ resblock_dilation_sizes,
1347
+ upsample_rates, upsample_initial_channel, upsample_kernel_sizes,
1348
+ gen_istft_n_fft, gen_istft_hop_size, subbands,
1349
+ gin_channels=gin_channels, is_onnx=is_onnx)
1350
+ elif istft_vits == True:
1351
+ print('iSTFT-VITS2')
1352
+ self.dec = iSTFT_Generator(inter_channels, resblock, resblock_kernel_sizes, resblock_dilation_sizes,
1353
+ upsample_rates, upsample_initial_channel, upsample_kernel_sizes, gen_istft_n_fft,
1354
+ gen_istft_hop_size, gin_channels=gin_channels, is_onnx=is_onnx)
1355
+ else:
1356
+ print('No iSTFT arguments found in json file')
1357
+ self.dec = Generator(inter_channels, resblock, resblock_kernel_sizes, resblock_dilation_sizes,
1358
+ upsample_rates,
1359
+ upsample_initial_channel, upsample_kernel_sizes, gin_channels=gin_channels) # vits 2
1360
+
1361
  self.enc_q = PosteriorEncoder(spec_channels, inter_channels, hidden_channels, 5, 1, 16,
1362
  gin_channels=gin_channels)
1363
+ # self.flow = ResidualCouplingBlock(inter_channels, hidden_channels, 5, 1, 4, gin_channels=gin_channels)
1364
+ self.flow = ResidualCouplingTransformersBlock(
1365
+ inter_channels,
1366
+ hidden_channels,
1367
+ 5,
1368
+ 1,
1369
+ 4,
1370
+ gin_channels=gin_channels,
1371
+ use_transformer_flows=self.use_transformer_flows,
1372
+ transformer_flow_type=self.transformer_flow_type
1373
+ )
1374
 
1375
  if use_sdp:
1376
  self.dp = StochasticDurationPredictor(hidden_channels, 192, 3, 0.5, 4, gin_channels=gin_channels)
1377
  else:
1378
  self.dp = DurationPredictor(hidden_channels, 256, 3, 0.5, gin_channels=gin_channels)
1379
 
1380
+ self.emb_g = nn.Embedding(n_speakers, gin_channels)
 
1381
 
1382
  def forward(self, x, x_lengths, y, y_lengths, sid=None):
1383
+ # x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths)
1384
+ g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
1385
 
1386
+ x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths, g=g) # vits2?
 
 
 
 
 
1387
  z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
1388
  z_p = self.flow(z, y_mask, g=g)
1389
 
 
1397
  neg_cent4 = torch.sum(-0.5 * (m_p ** 2) * s_p_sq_r, [1], keepdim=True) # [b, 1, t_s]
1398
  neg_cent = neg_cent1 + neg_cent2 + neg_cent3 + neg_cent4
1399
 
1400
+ if self.use_noise_scaled_mas:
1401
+ epsilon = torch.std(neg_cent) * torch.randn_like(neg_cent) * self.current_mas_noise_scale
1402
+ neg_cent = neg_cent + epsilon
1403
+
1404
  attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)
1405
  attn = monotonic_align.maximum_path(neg_cent, attn_mask.squeeze(1)).unsqueeze(1).detach()
1406
 
 
1408
  if self.use_sdp:
1409
  l_length = self.dp(x, x_mask, w, g=g)
1410
  l_length = l_length / torch.sum(x_mask)
1411
+ logw = self.dp(x, x_mask, g=g, reverse=True, noise_scale=1.)
1412
+ logw_ = torch.log(w + 1e-6) * x_mask
1413
  else:
1414
  logw_ = torch.log(w + 1e-6) * x_mask
1415
  logw = self.dp(x, x_mask, g=g)
 
1420
  logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(1, 2)
1421
 
1422
  z_slice, ids_slice = commons.rand_slice_segments(z, y_lengths, self.segment_size)
1423
+ o, o_mb = self.dec(z_slice, g=g)
1424
+ return o, o_mb, l_length, attn, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q), (x, logw, logw_)
1425
 
1426
  def infer(self, x, x_lengths, sid=None, noise_scale=1, length_scale=1, noise_scale_w=1., max_len=None):
1427
+ g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
 
 
 
 
1428
 
1429
+ x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths, g=g)
1430
  if self.use_sdp:
1431
  logw = self.dp(x, x_mask, g=g, reverse=True, noise_scale=noise_scale_w)
1432
  else:
 
1444
 
1445
  z_p = m_p + torch.randn_like(m_p) * torch.exp(logs_p) * noise_scale
1446
  z = self.flow(z_p, y_mask, g=g, reverse=True)
 
 
1447
 
1448
+ o, o_mb = self.dec((z * y_mask)[:, :, :max_len], g=g)
1449
+ return o, o_mb, attn, y_mask, (z, z_p, m_p, logs_p)
1450
+
1451
+
1452
+ #'''
1453
+ ## currently vits-2 is not capable of voice conversion
1454
+ # comment - choihkk : Assuming the use of the ResidualCouplingTransformersLayer2 module, it seems that voice conversion is possible
1455
  def voice_conversion(self, y, y_lengths, sid_src, sid_tgt):
1456
+ assert self.n_speakers > 0, "n_speakers have to be larger than 0."
1457
  g_src = self.emb_g(sid_src).unsqueeze(-1)
1458
  g_tgt = self.emb_g(sid_tgt).unsqueeze(-1)
1459
  z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g_src)
1460
  z_p = self.flow(z, y_mask, g=g_src)
1461
  z_hat = self.flow(z_p, y_mask, g=g_tgt, reverse=True)
1462
+ o_hat, o_hat_mb = self.dec(z_hat * y_mask, g=g_tgt)
1463
+ return o_hat, o_hat_mb, y_mask, (z, z_p, z_hat)
1464
+ #'''