zixian commited on
Commit
9422529
1 Parent(s): 16692c4

Update models.py

Browse files
Files changed (1) hide show
  1. models.py +533 -533
models.py CHANGED
@@ -1,533 +1,533 @@
1
- import copy
2
- import math
3
- import torch
4
- from torch import nn
5
- from torch.nn import functional as F
6
-
7
- import commons
8
- import modules
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
-
17
- class StochasticDurationPredictor(nn.Module):
18
- def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, n_flows=4, gin_channels=0):
19
- super().__init__()
20
- filter_channels = in_channels # it needs to be removed from future version.
21
- self.in_channels = in_channels
22
- self.filter_channels = filter_channels
23
- self.kernel_size = kernel_size
24
- self.p_dropout = p_dropout
25
- self.n_flows = n_flows
26
- self.gin_channels = gin_channels
27
-
28
- self.log_flow = modules.Log()
29
- self.flows = nn.ModuleList()
30
- self.flows.append(modules.ElementwiseAffine(2))
31
- for i in range(n_flows):
32
- self.flows.append(modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3))
33
- self.flows.append(modules.Flip())
34
-
35
- self.post_pre = nn.Conv1d(1, filter_channels, 1)
36
- self.post_proj = nn.Conv1d(filter_channels, filter_channels, 1)
37
- self.post_convs = modules.DDSConv(filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout)
38
- self.post_flows = nn.ModuleList()
39
- self.post_flows.append(modules.ElementwiseAffine(2))
40
- for i in range(4):
41
- self.post_flows.append(modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3))
42
- self.post_flows.append(modules.Flip())
43
-
44
- self.pre = nn.Conv1d(in_channels, filter_channels, 1)
45
- self.proj = nn.Conv1d(filter_channels, filter_channels, 1)
46
- self.convs = modules.DDSConv(filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout)
47
- if gin_channels != 0:
48
- self.cond = nn.Conv1d(gin_channels, filter_channels, 1)
49
-
50
- def forward(self, x, x_mask, w=None, g=None, reverse=False, noise_scale=1.0):
51
- x = torch.detach(x)
52
- x = self.pre(x)
53
- if g is not None:
54
- g = torch.detach(g)
55
- x = x + self.cond(g)
56
- x = self.convs(x, x_mask)
57
- x = self.proj(x) * x_mask
58
-
59
- if not reverse:
60
- flows = self.flows
61
- assert w is not None
62
-
63
- logdet_tot_q = 0
64
- h_w = self.post_pre(w)
65
- h_w = self.post_convs(h_w, x_mask)
66
- h_w = self.post_proj(h_w) * x_mask
67
- e_q = torch.randn(w.size(0), 2, w.size(2)).to(device=x.device, dtype=x.dtype) * x_mask
68
- z_q = e_q
69
- for flow in self.post_flows:
70
- z_q, logdet_q = flow(z_q, x_mask, g=(x + h_w))
71
- logdet_tot_q += logdet_q
72
- z_u, z1 = torch.split(z_q, [1, 1], 1)
73
- u = torch.sigmoid(z_u) * x_mask
74
- z0 = (w - u) * x_mask
75
- logdet_tot_q += torch.sum((F.logsigmoid(z_u) + F.logsigmoid(-z_u)) * x_mask, [1,2])
76
- logq = torch.sum(-0.5 * (math.log(2*math.pi) + (e_q**2)) * x_mask, [1,2]) - logdet_tot_q
77
-
78
- logdet_tot = 0
79
- z0, logdet = self.log_flow(z0, x_mask)
80
- logdet_tot += logdet
81
- z = torch.cat([z0, z1], 1)
82
- for flow in flows:
83
- z, logdet = flow(z, x_mask, g=x, reverse=reverse)
84
- logdet_tot = logdet_tot + logdet
85
- nll = torch.sum(0.5 * (math.log(2*math.pi) + (z**2)) * x_mask, [1,2]) - logdet_tot
86
- return nll + logq # [b]
87
- else:
88
- flows = list(reversed(self.flows))
89
- flows = flows[:-2] + [flows[-1]] # remove a useless vflow
90
- z = torch.randn(x.size(0), 2, x.size(2)).to(device=x.device, dtype=x.dtype) * noise_scale
91
- for flow in flows:
92
- z = flow(z, x_mask, g=x, reverse=reverse)
93
- z0, z1 = torch.split(z, [1, 1], 1)
94
- logw = z0
95
- return logw
96
-
97
-
98
- class DurationPredictor(nn.Module):
99
- def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, gin_channels=0):
100
- super().__init__()
101
-
102
- self.in_channels = in_channels
103
- self.filter_channels = filter_channels
104
- self.kernel_size = kernel_size
105
- self.p_dropout = p_dropout
106
- self.gin_channels = gin_channels
107
-
108
- self.drop = nn.Dropout(p_dropout)
109
- self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size, padding=kernel_size//2)
110
- self.norm_1 = modules.LayerNorm(filter_channels)
111
- self.conv_2 = nn.Conv1d(filter_channels, filter_channels, kernel_size, padding=kernel_size//2)
112
- self.norm_2 = modules.LayerNorm(filter_channels)
113
- self.proj = nn.Conv1d(filter_channels, 1, 1)
114
-
115
- if gin_channels != 0:
116
- self.cond = nn.Conv1d(gin_channels, in_channels, 1)
117
-
118
- def forward(self, x, x_mask, g=None):
119
- x = torch.detach(x)
120
- if g is not None:
121
- g = torch.detach(g)
122
- x = x + self.cond(g)
123
- x = self.conv_1(x * x_mask)
124
- x = torch.relu(x)
125
- x = self.norm_1(x)
126
- x = self.drop(x)
127
- x = self.conv_2(x * x_mask)
128
- x = torch.relu(x)
129
- x = self.norm_2(x)
130
- x = self.drop(x)
131
- x = self.proj(x * x_mask)
132
- return x * x_mask
133
-
134
-
135
- class TextEncoder(nn.Module):
136
- def __init__(self,
137
- n_vocab,
138
- out_channels,
139
- hidden_channels,
140
- filter_channels,
141
- n_heads,
142
- n_layers,
143
- kernel_size,
144
- p_dropout):
145
- super().__init__()
146
- self.n_vocab = n_vocab
147
- self.out_channels = out_channels
148
- self.hidden_channels = hidden_channels
149
- self.filter_channels = filter_channels
150
- self.n_heads = n_heads
151
- self.n_layers = n_layers
152
- self.kernel_size = kernel_size
153
- self.p_dropout = p_dropout
154
-
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,
160
- filter_channels,
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
- x = self.emb(x) * math.sqrt(self.hidden_channels) # [b, t, h]
169
- x = torch.transpose(x, 1, -1) # [b, h, t]
170
- x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
171
-
172
- x = self.encoder(x * x_mask, x_mask)
173
- stats = self.proj(x) * x_mask
174
-
175
- m, logs = torch.split(stats, self.out_channels, dim=1)
176
- return x, m, logs, x_mask
177
-
178
-
179
- class ResidualCouplingBlock(nn.Module):
180
- def __init__(self,
181
- channels,
182
- hidden_channels,
183
- kernel_size,
184
- dilation_rate,
185
- n_layers,
186
- n_flows=4,
187
- gin_channels=0):
188
- super().__init__()
189
- self.channels = channels
190
- self.hidden_channels = hidden_channels
191
- self.kernel_size = kernel_size
192
- self.dilation_rate = dilation_rate
193
- self.n_layers = n_layers
194
- self.n_flows = n_flows
195
- self.gin_channels = gin_channels
196
-
197
- self.flows = nn.ModuleList()
198
- for i in range(n_flows):
199
- self.flows.append(modules.ResidualCouplingLayer(channels, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels, mean_only=True))
200
- self.flows.append(modules.Flip())
201
-
202
- def forward(self, x, x_mask, g=None, reverse=False):
203
- if not reverse:
204
- for flow in self.flows:
205
- x, _ = flow(x, x_mask, g=g, reverse=reverse)
206
- else:
207
- for flow in reversed(self.flows):
208
- x = flow(x, x_mask, g=g, reverse=reverse)
209
- return x
210
-
211
-
212
- class PosteriorEncoder(nn.Module):
213
- def __init__(self,
214
- in_channels,
215
- out_channels,
216
- hidden_channels,
217
- kernel_size,
218
- dilation_rate,
219
- n_layers,
220
- gin_channels=0):
221
- super().__init__()
222
- self.in_channels = in_channels
223
- self.out_channels = out_channels
224
- self.hidden_channels = hidden_channels
225
- self.kernel_size = kernel_size
226
- self.dilation_rate = dilation_rate
227
- self.n_layers = n_layers
228
- self.gin_channels = gin_channels
229
-
230
- self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
231
- self.enc = modules.WN(hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels)
232
- self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
233
-
234
- def forward(self, x, x_lengths, g=None):
235
- x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
236
- x = self.pre(x) * x_mask
237
- x = self.enc(x, x_mask, g=g)
238
- stats = self.proj(x) * x_mask
239
- m, logs = torch.split(stats, self.out_channels, dim=1)
240
- z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask
241
- return z, m, logs, x_mask
242
-
243
-
244
- class Generator(torch.nn.Module):
245
- def __init__(self, initial_channel, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, upsample_initial_channel, upsample_kernel_sizes, gin_channels=0):
246
- super(Generator, self).__init__()
247
- self.num_kernels = len(resblock_kernel_sizes)
248
- self.num_upsamples = len(upsample_rates)
249
- self.conv_pre = Conv1d(initial_channel, upsample_initial_channel, 7, 1, padding=3)
250
- resblock = modules.ResBlock1 if resblock == '1' else modules.ResBlock2
251
-
252
- self.ups = nn.ModuleList()
253
- for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
254
- self.ups.append(weight_norm(
255
- ConvTranspose1d(upsample_initial_channel//(2**i), upsample_initial_channel//(2**(i+1)),
256
- k, u, padding=(k-u)//2)))
257
-
258
- self.resblocks = nn.ModuleList()
259
- for i in range(len(self.ups)):
260
- ch = upsample_initial_channel//(2**(i+1))
261
- for j, (k, d) in enumerate(zip(resblock_kernel_sizes, resblock_dilation_sizes)):
262
- self.resblocks.append(resblock(ch, k, d))
263
-
264
- self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False)
265
- self.ups.apply(init_weights)
266
-
267
- if gin_channels != 0:
268
- self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
269
-
270
- def forward(self, x, g=None):
271
- x = self.conv_pre(x)
272
- if g is not None:
273
- x = x + self.cond(g)
274
-
275
- for i in range(self.num_upsamples):
276
- x = F.leaky_relu(x, modules.LRELU_SLOPE)
277
- x = self.ups[i](x)
278
- xs = None
279
- for j in range(self.num_kernels):
280
- if xs is None:
281
- xs = self.resblocks[i*self.num_kernels+j](x)
282
- else:
283
- xs += self.resblocks[i*self.num_kernels+j](x)
284
- x = xs / self.num_kernels
285
- x = F.leaky_relu(x)
286
- x = self.conv_post(x)
287
- x = torch.tanh(x)
288
-
289
- return x
290
-
291
- def remove_weight_norm(self):
292
- print('Removing weight norm...')
293
- for l in self.ups:
294
- remove_weight_norm(l)
295
- for l in self.resblocks:
296
- l.remove_weight_norm()
297
-
298
-
299
- class DiscriminatorP(torch.nn.Module):
300
- def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False):
301
- super(DiscriminatorP, self).__init__()
302
- self.period = period
303
- self.use_spectral_norm = use_spectral_norm
304
- norm_f = weight_norm if use_spectral_norm == False else spectral_norm
305
- self.convs = nn.ModuleList([
306
- norm_f(Conv2d(1, 32, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
307
- norm_f(Conv2d(32, 128, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
308
- norm_f(Conv2d(128, 512, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
309
- norm_f(Conv2d(512, 1024, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
310
- norm_f(Conv2d(1024, 1024, (kernel_size, 1), 1, padding=(get_padding(kernel_size, 1), 0))),
311
- ])
312
- self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
313
-
314
- def forward(self, x):
315
- fmap = []
316
-
317
- # 1d to 2d
318
- b, c, t = x.shape
319
- if t % self.period != 0: # pad first
320
- n_pad = self.period - (t % self.period)
321
- x = F.pad(x, (0, n_pad), "reflect")
322
- t = t + n_pad
323
- x = x.view(b, c, t // self.period, self.period)
324
-
325
- for l in self.convs:
326
- x = l(x)
327
- x = F.leaky_relu(x, modules.LRELU_SLOPE)
328
- fmap.append(x)
329
- x = self.conv_post(x)
330
- fmap.append(x)
331
- x = torch.flatten(x, 1, -1)
332
-
333
- return x, fmap
334
-
335
-
336
- class DiscriminatorS(torch.nn.Module):
337
- def __init__(self, use_spectral_norm=False):
338
- super(DiscriminatorS, self).__init__()
339
- norm_f = weight_norm if use_spectral_norm == False else spectral_norm
340
- self.convs = nn.ModuleList([
341
- norm_f(Conv1d(1, 16, 15, 1, padding=7)),
342
- norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)),
343
- norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)),
344
- norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)),
345
- norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)),
346
- norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
347
- ])
348
- self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
349
-
350
- def forward(self, x):
351
- fmap = []
352
-
353
- for l in self.convs:
354
- x = l(x)
355
- x = F.leaky_relu(x, modules.LRELU_SLOPE)
356
- fmap.append(x)
357
- x = self.conv_post(x)
358
- fmap.append(x)
359
- x = torch.flatten(x, 1, -1)
360
-
361
- return x, fmap
362
-
363
-
364
- class MultiPeriodDiscriminator(torch.nn.Module):
365
- def __init__(self, use_spectral_norm=False):
366
- super(MultiPeriodDiscriminator, self).__init__()
367
- periods = [2,3,5,7,11]
368
-
369
- discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
370
- discs = discs + [DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods]
371
- self.discriminators = nn.ModuleList(discs)
372
-
373
- def forward(self, y, y_hat):
374
- y_d_rs = []
375
- y_d_gs = []
376
- fmap_rs = []
377
- fmap_gs = []
378
- for i, d in enumerate(self.discriminators):
379
- y_d_r, fmap_r = d(y)
380
- y_d_g, fmap_g = d(y_hat)
381
- y_d_rs.append(y_d_r)
382
- y_d_gs.append(y_d_g)
383
- fmap_rs.append(fmap_r)
384
- fmap_gs.append(fmap_g)
385
-
386
- return y_d_rs, y_d_gs, fmap_rs, fmap_gs
387
-
388
-
389
-
390
- class SynthesizerTrn(nn.Module):
391
- """
392
- Synthesizer for Training
393
- """
394
-
395
- def __init__(self,
396
- n_vocab,
397
- spec_channels,
398
- segment_size,
399
- inter_channels,
400
- hidden_channels,
401
- filter_channels,
402
- n_heads,
403
- n_layers,
404
- kernel_size,
405
- p_dropout,
406
- resblock,
407
- resblock_kernel_sizes,
408
- resblock_dilation_sizes,
409
- upsample_rates,
410
- upsample_initial_channel,
411
- upsample_kernel_sizes,
412
- n_speakers=0,
413
- gin_channels=0,
414
- use_sdp=True,
415
- **kwargs):
416
-
417
- super().__init__()
418
- self.n_vocab = n_vocab
419
- self.spec_channels = spec_channels
420
- self.inter_channels = inter_channels
421
- self.hidden_channels = hidden_channels
422
- self.filter_channels = filter_channels
423
- self.n_heads = n_heads
424
- self.n_layers = n_layers
425
- self.kernel_size = kernel_size
426
- self.p_dropout = p_dropout
427
- self.resblock = resblock
428
- self.resblock_kernel_sizes = resblock_kernel_sizes
429
- self.resblock_dilation_sizes = resblock_dilation_sizes
430
- self.upsample_rates = upsample_rates
431
- self.upsample_initial_channel = upsample_initial_channel
432
- self.upsample_kernel_sizes = upsample_kernel_sizes
433
- self.segment_size = segment_size
434
- self.n_speakers = n_speakers
435
- self.gin_channels = gin_channels
436
-
437
- self.use_sdp = use_sdp
438
-
439
- self.enc_p = TextEncoder(n_vocab,
440
- inter_channels,
441
- hidden_channels,
442
- filter_channels,
443
- n_heads,
444
- n_layers,
445
- kernel_size,
446
- p_dropout)
447
- self.dec = Generator(inter_channels, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, upsample_initial_channel, upsample_kernel_sizes, gin_channels=gin_channels)
448
- self.enc_q = PosteriorEncoder(spec_channels, inter_channels, hidden_channels, 5, 1, 16, gin_channels=gin_channels)
449
- self.flow = ResidualCouplingBlock(inter_channels, hidden_channels, 5, 1, 4, gin_channels=gin_channels)
450
-
451
- if use_sdp:
452
- self.dp = StochasticDurationPredictor(hidden_channels, 192, 3, 0.5, 4, gin_channels=gin_channels)
453
- else:
454
- self.dp = DurationPredictor(hidden_channels, 256, 3, 0.5, gin_channels=gin_channels)
455
-
456
- if n_speakers >= 1:
457
- self.emb_g = nn.Embedding(n_speakers, gin_channels)
458
-
459
- def forward(self, x, x_lengths, y, y_lengths, sid=None):
460
-
461
- x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths)
462
- if self.n_speakers > 0:
463
- g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
464
- else:
465
- g = None
466
-
467
- z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
468
- z_p = self.flow(z, y_mask, g=g)
469
-
470
- with torch.no_grad():
471
- # negative cross-entropy
472
- s_p_sq_r = torch.exp(-2 * logs_p) # [b, d, t]
473
- neg_cent1 = torch.sum(-0.5 * math.log(2 * math.pi) - logs_p, [1], keepdim=True) # [b, 1, t_s]
474
- neg_cent2 = torch.matmul(-0.5 * (z_p ** 2).transpose(1, 2), s_p_sq_r) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s]
475
- neg_cent3 = torch.matmul(z_p.transpose(1, 2), (m_p * s_p_sq_r)) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s]
476
- neg_cent4 = torch.sum(-0.5 * (m_p ** 2) * s_p_sq_r, [1], keepdim=True) # [b, 1, t_s]
477
- neg_cent = neg_cent1 + neg_cent2 + neg_cent3 + neg_cent4
478
-
479
- attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)
480
- attn = monotonic_align.maximum_path(neg_cent, attn_mask.squeeze(1)).unsqueeze(1).detach()
481
-
482
- w = attn.sum(2)
483
- if self.use_sdp:
484
- l_length = self.dp(x, x_mask, w, g=g)
485
- l_length = l_length / torch.sum(x_mask)
486
- else:
487
- logw_ = torch.log(w + 1e-6) * x_mask
488
- logw = self.dp(x, x_mask, g=g)
489
- l_length = torch.sum((logw - logw_)**2, [1,2]) / torch.sum(x_mask) # for averaging
490
-
491
- # expand prior
492
- m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(1, 2)
493
- logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(1, 2)
494
-
495
- z_slice, ids_slice = commons.rand_slice_segments(z, y_lengths, self.segment_size)
496
- o = self.dec(z_slice, g=g)
497
- return o, l_length, attn, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q)
498
-
499
- def infer(self, x, x_lengths, sid=None, noise_scale=1, length_scale=1, noise_scale_w=1., max_len=None):
500
- x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths)
501
- if self.n_speakers > 0:
502
- g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
503
- else:
504
- g = None
505
-
506
- if self.use_sdp:
507
- logw = self.dp(x, x_mask, g=g, reverse=True, noise_scale=noise_scale_w)
508
- else:
509
- logw = self.dp(x, x_mask, g=g)
510
- w = torch.exp(logw) * x_mask * length_scale
511
- w_ceil = torch.ceil(w)
512
- y_lengths = torch.clamp_min(torch.sum(w_ceil, [1, 2]), 1).long()
513
- y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, None), 1).to(x_mask.dtype)
514
- attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)
515
- attn = commons.generate_path(w_ceil, attn_mask)
516
-
517
- m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(1, 2) # [b, t', t], [b, t, d] -> [b, d, t']
518
- logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(1, 2) # [b, t', t], [b, t, d] -> [b, d, t']
519
-
520
- z_p = m_p + torch.randn_like(m_p) * torch.exp(logs_p) * noise_scale
521
- z = self.flow(z_p, y_mask, g=g, reverse=True)
522
- o = self.dec((z * y_mask)[:,:,:max_len], g=g)
523
- return o, attn, y_mask, (z, z_p, m_p, logs_p)
524
-
525
- def voice_conversion(self, y, y_lengths, sid_src, sid_tgt):
526
- assert self.n_speakers > 0, "n_speakers have to be larger than 0."
527
- g_src = self.emb_g(sid_src).unsqueeze(-1)
528
- g_tgt = self.emb_g(sid_tgt).unsqueeze(-1)
529
- z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g_src)
530
- z_p = self.flow(z, y_mask, g=g_src)
531
- z_hat = self.flow(z_p, y_mask, g=g_tgt, reverse=True)
532
- o_hat = self.dec(z_hat * y_mask, g=g_tgt)
533
- return o_hat, y_mask, (z, z_p, z_hat)
 
1
+ import copy
2
+ import math
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn import functional as F
6
+
7
+ import commons
8
+ import modules
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
+
17
+ class StochasticDurationPredictor(nn.Module):
18
+ def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, n_flows=4, gin_channels=0):
19
+ super().__init__()
20
+ filter_channels = in_channels # it needs to be removed from future version.
21
+ self.in_channels = in_channels
22
+ self.filter_channels = filter_channels
23
+ self.kernel_size = kernel_size
24
+ self.p_dropout = p_dropout
25
+ self.n_flows = n_flows
26
+ self.gin_channels = gin_channels
27
+
28
+ self.log_flow = modules.Log()
29
+ self.flows = nn.ModuleList()
30
+ self.flows.append(modules.ElementwiseAffine(2))
31
+ for i in range(n_flows):
32
+ self.flows.append(modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3))
33
+ self.flows.append(modules.Flip())
34
+
35
+ self.post_pre = nn.Conv1d(1, filter_channels, 1)
36
+ self.post_proj = nn.Conv1d(filter_channels, filter_channels, 1)
37
+ self.post_convs = modules.DDSConv(filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout)
38
+ self.post_flows = nn.ModuleList()
39
+ self.post_flows.append(modules.ElementwiseAffine(2))
40
+ for i in range(4):
41
+ self.post_flows.append(modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3))
42
+ self.post_flows.append(modules.Flip())
43
+
44
+ self.pre = nn.Conv1d(in_channels, filter_channels, 1)
45
+ self.proj = nn.Conv1d(filter_channels, filter_channels, 1)
46
+ self.convs = modules.DDSConv(filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout)
47
+ if gin_channels != 0:
48
+ self.cond = nn.Conv1d(gin_channels, filter_channels, 1)
49
+
50
+ def forward(self, x, x_mask, w=None, g=None, reverse=False, noise_scale=1.0):
51
+ x = torch.detach(x)
52
+ x = self.pre(x)
53
+ if g is not None:
54
+ g = torch.detach(g)
55
+ x = x + self.cond(g)
56
+ x = self.convs(x, x_mask)
57
+ x = self.proj(x) * x_mask
58
+
59
+ if not reverse:
60
+ flows = self.flows
61
+ assert w is not None
62
+
63
+ logdet_tot_q = 0
64
+ h_w = self.post_pre(w)
65
+ h_w = self.post_convs(h_w, x_mask)
66
+ h_w = self.post_proj(h_w) * x_mask
67
+ e_q = torch.randn(w.size(0), 2, w.size(2)).to(device=x.device, dtype=x.dtype) * x_mask
68
+ z_q = e_q
69
+ for flow in self.post_flows:
70
+ z_q, logdet_q = flow(z_q, x_mask, g=(x + h_w))
71
+ logdet_tot_q += logdet_q
72
+ z_u, z1 = torch.split(z_q, [1, 1], 1)
73
+ u = torch.sigmoid(z_u) * x_mask
74
+ z0 = (w - u) * x_mask
75
+ logdet_tot_q += torch.sum((F.logsigmoid(z_u) + F.logsigmoid(-z_u)) * x_mask, [1,2])
76
+ logq = torch.sum(-0.5 * (math.log(2*math.pi) + (e_q**2)) * x_mask, [1,2]) - logdet_tot_q
77
+
78
+ logdet_tot = 0
79
+ z0, logdet = self.log_flow(z0, x_mask)
80
+ logdet_tot += logdet
81
+ z = torch.cat([z0, z1], 1)
82
+ for flow in flows:
83
+ z, logdet = flow(z, x_mask, g=x, reverse=reverse)
84
+ logdet_tot = logdet_tot + logdet
85
+ nll = torch.sum(0.5 * (math.log(2*math.pi) + (z**2)) * x_mask, [1,2]) - logdet_tot
86
+ return nll + logq # [b]
87
+ else:
88
+ flows = list(reversed(self.flows))
89
+ flows = flows[:-2] + [flows[-1]] # remove a useless vflow
90
+ z = torch.randn(x.size(0), 2, x.size(2)).to(device=x.device, dtype=x.dtype) * noise_scale
91
+ for flow in flows:
92
+ z = flow(z, x_mask, g=x, reverse=reverse)
93
+ z0, z1 = torch.split(z, [1, 1], 1)
94
+ logw = z0
95
+ return logw
96
+
97
+
98
+ class DurationPredictor(nn.Module):
99
+ def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, gin_channels=0):
100
+ super().__init__()
101
+
102
+ self.in_channels = in_channels
103
+ self.filter_channels = filter_channels
104
+ self.kernel_size = kernel_size
105
+ self.p_dropout = p_dropout
106
+ self.gin_channels = gin_channels
107
+
108
+ self.drop = nn.Dropout(p_dropout)
109
+ self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size, padding=kernel_size//2)
110
+ self.norm_1 = modules.LayerNorm(filter_channels)
111
+ self.conv_2 = nn.Conv1d(filter_channels, filter_channels, kernel_size, padding=kernel_size//2)
112
+ self.norm_2 = modules.LayerNorm(filter_channels)
113
+ self.proj = nn.Conv1d(filter_channels, 1, 1)
114
+
115
+ if gin_channels != 0:
116
+ self.cond = nn.Conv1d(gin_channels, in_channels, 1)
117
+
118
+ def forward(self, x, x_mask, g=None):
119
+ x = torch.detach(x)
120
+ if g is not None:
121
+ g = torch.detach(g)
122
+ x = x + self.cond(g)
123
+ x = self.conv_1(x * x_mask)
124
+ x = torch.relu(x)
125
+ x = self.norm_1(x)
126
+ x = self.drop(x)
127
+ x = self.conv_2(x * x_mask)
128
+ x = torch.relu(x)
129
+ x = self.norm_2(x)
130
+ x = self.drop(x)
131
+ x = self.proj(x * x_mask)
132
+ return x * x_mask
133
+
134
+
135
+ class TextEncoder(nn.Module):
136
+ def __init__(self,
137
+ n_vocab,
138
+ out_channels,
139
+ hidden_channels,
140
+ filter_channels,
141
+ n_heads,
142
+ n_layers,
143
+ kernel_size,
144
+ p_dropout):
145
+ super().__init__()
146
+ self.n_vocab = n_vocab
147
+ self.out_channels = out_channels
148
+ self.hidden_channels = hidden_channels
149
+ self.filter_channels = filter_channels
150
+ self.n_heads = n_heads
151
+ self.n_layers = n_layers
152
+ self.kernel_size = kernel_size
153
+ self.p_dropout = p_dropout
154
+
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,
160
+ filter_channels,
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
+ x = self.emb(x) * math.sqrt(self.hidden_channels) # [b, t, h]
169
+ x = torch.transpose(x, 1, -1) # [b, h, t]
170
+ x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
171
+
172
+ x = self.encoder(x * x_mask, x_mask)
173
+ stats = self.proj(x) * x_mask
174
+
175
+ m, logs = torch.split(stats, self.out_channels, dim=1)
176
+ return x, m, logs, x_mask
177
+
178
+
179
+ class ResidualCouplingBlock(nn.Module):
180
+ def __init__(self,
181
+ channels,
182
+ hidden_channels,
183
+ kernel_size,
184
+ dilation_rate,
185
+ n_layers,
186
+ n_flows=4,
187
+ gin_channels=0):
188
+ super().__init__()
189
+ self.channels = channels
190
+ self.hidden_channels = hidden_channels
191
+ self.kernel_size = kernel_size
192
+ self.dilation_rate = dilation_rate
193
+ self.n_layers = n_layers
194
+ self.n_flows = n_flows
195
+ self.gin_channels = gin_channels
196
+
197
+ self.flows = nn.ModuleList()
198
+ for i in range(n_flows):
199
+ self.flows.append(modules.ResidualCouplingLayer(channels, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels, mean_only=True))
200
+ self.flows.append(modules.Flip())
201
+
202
+ def forward(self, x, x_mask, g=None, reverse=False):
203
+ if not reverse:
204
+ for flow in self.flows:
205
+ x, _ = flow(x, x_mask, g=g, reverse=reverse)
206
+ else:
207
+ for flow in reversed(self.flows):
208
+ x = flow(x, x_mask, g=g, reverse=reverse)
209
+ return x
210
+
211
+
212
+ class PosteriorEncoder(nn.Module):
213
+ def __init__(self,
214
+ in_channels,
215
+ out_channels,
216
+ hidden_channels,
217
+ kernel_size,
218
+ dilation_rate,
219
+ n_layers,
220
+ gin_channels=0):
221
+ super().__init__()
222
+ self.in_channels = in_channels
223
+ self.out_channels = out_channels
224
+ self.hidden_channels = hidden_channels
225
+ self.kernel_size = kernel_size
226
+ self.dilation_rate = dilation_rate
227
+ self.n_layers = n_layers
228
+ self.gin_channels = gin_channels
229
+
230
+ self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
231
+ self.enc = modules.WN(hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels)
232
+ self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
233
+
234
+ def forward(self, x, x_lengths, g=None):
235
+ x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
236
+ x = self.pre(x) * x_mask
237
+ x = self.enc(x, x_mask, g=g)
238
+ stats = self.proj(x) * x_mask
239
+ m, logs = torch.split(stats, self.out_channels, dim=1)
240
+ z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask
241
+ return z, m, logs, x_mask
242
+
243
+
244
+ class Generator(torch.nn.Module):
245
+ def __init__(self, initial_channel, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, upsample_initial_channel, upsample_kernel_sizes, gin_channels=0):
246
+ super(Generator, self).__init__()
247
+ self.num_kernels = len(resblock_kernel_sizes)
248
+ self.num_upsamples = len(upsample_rates)
249
+ self.conv_pre = Conv1d(initial_channel, upsample_initial_channel, 7, 1, padding=3)
250
+ resblock = modules.ResBlock1 if resblock == '1' else modules.ResBlock2
251
+
252
+ self.ups = nn.ModuleList()
253
+ for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
254
+ self.ups.append(weight_norm(
255
+ ConvTranspose1d(upsample_initial_channel//(2**i), upsample_initial_channel//(2**(i+1)),
256
+ k, u, padding=(k-u)//2)))
257
+
258
+ self.resblocks = nn.ModuleList()
259
+ for i in range(len(self.ups)):
260
+ ch = upsample_initial_channel//(2**(i+1))
261
+ for j, (k, d) in enumerate(zip(resblock_kernel_sizes, resblock_dilation_sizes)):
262
+ self.resblocks.append(resblock(ch, k, d))
263
+
264
+ self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False)
265
+ self.ups.apply(init_weights)
266
+
267
+ if gin_channels != 0:
268
+ self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
269
+
270
+ def forward(self, x, g=None):
271
+ x = self.conv_pre(x)
272
+ if g is not None:
273
+ x = x + self.cond(g)
274
+
275
+ for i in range(self.num_upsamples):
276
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
277
+ x = self.ups[i](x)
278
+ xs = None
279
+ for j in range(self.num_kernels):
280
+ if xs is None:
281
+ xs = self.resblocks[i*self.num_kernels+j](x)
282
+ else:
283
+ xs += self.resblocks[i*self.num_kernels+j](x)
284
+ x = xs / self.num_kernels
285
+ x = F.leaky_relu(x)
286
+ x = self.conv_post(x)
287
+ x = torch.tanh(x)
288
+
289
+ return x
290
+
291
+ def remove_weight_norm(self):
292
+ print('Removing weight norm...')
293
+ for l in self.ups:
294
+ remove_weight_norm(l)
295
+ for l in self.resblocks:
296
+ l.remove_weight_norm()
297
+
298
+
299
+ class DiscriminatorP(torch.nn.Module):
300
+ def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False):
301
+ super(DiscriminatorP, self).__init__()
302
+ self.period = period
303
+ self.use_spectral_norm = use_spectral_norm
304
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
305
+ self.convs = nn.ModuleList([
306
+ norm_f(Conv2d(1, 32, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
307
+ norm_f(Conv2d(32, 128, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
308
+ norm_f(Conv2d(128, 512, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
309
+ norm_f(Conv2d(512, 1024, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
310
+ norm_f(Conv2d(1024, 1024, (kernel_size, 1), 1, padding=(get_padding(kernel_size, 1), 0))),
311
+ ])
312
+ self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
313
+
314
+ def forward(self, x):
315
+ fmap = []
316
+
317
+ # 1d to 2d
318
+ b, c, t = x.shape
319
+ if t % self.period != 0: # pad first
320
+ n_pad = self.period - (t % self.period)
321
+ x = F.pad(x, (0, n_pad), "reflect")
322
+ t = t + n_pad
323
+ x = x.view(b, c, t // self.period, self.period)
324
+
325
+ for l in self.convs:
326
+ x = l(x)
327
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
328
+ fmap.append(x)
329
+ x = self.conv_post(x)
330
+ fmap.append(x)
331
+ x = torch.flatten(x, 1, -1)
332
+
333
+ return x, fmap
334
+
335
+
336
+ class DiscriminatorS(torch.nn.Module):
337
+ def __init__(self, use_spectral_norm=False):
338
+ super(DiscriminatorS, self).__init__()
339
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
340
+ self.convs = nn.ModuleList([
341
+ norm_f(Conv1d(1, 16, 15, 1, padding=7)),
342
+ norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)),
343
+ norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)),
344
+ norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)),
345
+ norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)),
346
+ norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
347
+ ])
348
+ self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
349
+
350
+ def forward(self, x):
351
+ fmap = []
352
+
353
+ for l in self.convs:
354
+ x = l(x)
355
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
356
+ fmap.append(x)
357
+ x = self.conv_post(x)
358
+ fmap.append(x)
359
+ x = torch.flatten(x, 1, -1)
360
+
361
+ return x, fmap
362
+
363
+
364
+ class MultiPeriodDiscriminator(torch.nn.Module):
365
+ def __init__(self, use_spectral_norm=False):
366
+ super(MultiPeriodDiscriminator, self).__init__()
367
+ periods = [2,3,5,7,11]
368
+
369
+ discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
370
+ discs = discs + [DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods]
371
+ self.discriminators = nn.ModuleList(discs)
372
+
373
+ def forward(self, y, y_hat):
374
+ y_d_rs = []
375
+ y_d_gs = []
376
+ fmap_rs = []
377
+ fmap_gs = []
378
+ for i, d in enumerate(self.discriminators):
379
+ y_d_r, fmap_r = d(y)
380
+ y_d_g, fmap_g = d(y_hat)
381
+ y_d_rs.append(y_d_r)
382
+ y_d_gs.append(y_d_g)
383
+ fmap_rs.append(fmap_r)
384
+ fmap_gs.append(fmap_g)
385
+
386
+ return y_d_rs, y_d_gs, fmap_rs, fmap_gs
387
+
388
+
389
+
390
+ class SynthesizerTrn(nn.Module):
391
+ """
392
+ Synthesizer for Training
393
+ """
394
+
395
+ def __init__(self,
396
+ n_vocab,
397
+ spec_channels,
398
+ segment_size,
399
+ inter_channels,
400
+ hidden_channels,
401
+ filter_channels,
402
+ n_heads,
403
+ n_layers,
404
+ kernel_size,
405
+ p_dropout,
406
+ resblock,
407
+ resblock_kernel_sizes,
408
+ resblock_dilation_sizes,
409
+ upsample_rates,
410
+ upsample_initial_channel,
411
+ upsample_kernel_sizes,
412
+ n_speakers=0,
413
+ gin_channels=0,
414
+ use_sdp=True,
415
+ **kwargs):
416
+
417
+ super().__init__()
418
+ self.n_vocab = n_vocab
419
+ self.spec_channels = spec_channels
420
+ self.inter_channels = inter_channels
421
+ self.hidden_channels = hidden_channels
422
+ self.filter_channels = filter_channels
423
+ self.n_heads = n_heads
424
+ self.n_layers = n_layers
425
+ self.kernel_size = kernel_size
426
+ self.p_dropout = p_dropout
427
+ self.resblock = resblock
428
+ self.resblock_kernel_sizes = resblock_kernel_sizes
429
+ self.resblock_dilation_sizes = resblock_dilation_sizes
430
+ self.upsample_rates = upsample_rates
431
+ self.upsample_initial_channel = upsample_initial_channel
432
+ self.upsample_kernel_sizes = upsample_kernel_sizes
433
+ self.segment_size = segment_size
434
+ self.n_speakers = n_speakers
435
+ self.gin_channels = gin_channels
436
+
437
+ self.use_sdp = use_sdp
438
+
439
+ self.enc_p = TextEncoder(n_vocab,
440
+ inter_channels,
441
+ hidden_channels,
442
+ filter_channels,
443
+ n_heads,
444
+ n_layers,
445
+ kernel_size,
446
+ p_dropout)
447
+ self.dec = Generator(inter_channels, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, upsample_initial_channel, upsample_kernel_sizes, gin_channels=gin_channels)
448
+ self.enc_q = PosteriorEncoder(spec_channels, inter_channels, hidden_channels, 5, 1, 16, gin_channels=gin_channels)
449
+ self.flow = ResidualCouplingBlock(inter_channels, hidden_channels, 5, 1, 4, gin_channels=gin_channels)
450
+
451
+ if use_sdp:
452
+ self.dp = StochasticDurationPredictor(hidden_channels, 192, 3, 0.5, 4, gin_channels=gin_channels)
453
+ else:
454
+ self.dp = DurationPredictor(hidden_channels, 256, 3, 0.5, gin_channels=gin_channels)
455
+
456
+ if n_speakers >= 1:
457
+ self.emb_g = nn.Embedding(n_speakers, gin_channels)
458
+
459
+ def forward(self, x, x_lengths, y, y_lengths, sid=None):
460
+
461
+ x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths)
462
+ if self.n_speakers > 0:
463
+ g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
464
+ else:
465
+ g = None
466
+
467
+ z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
468
+ z_p = self.flow(z, y_mask, g=g)
469
+
470
+ with torch.no_grad():
471
+ # negative cross-entropy
472
+ s_p_sq_r = torch.exp(-2 * logs_p) # [b, d, t]
473
+ neg_cent1 = torch.sum(-0.5 * math.log(2 * math.pi) - logs_p, [1], keepdim=True) # [b, 1, t_s]
474
+ neg_cent2 = torch.matmul(-0.5 * (z_p ** 2).transpose(1, 2), s_p_sq_r) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s]
475
+ neg_cent3 = torch.matmul(z_p.transpose(1, 2), (m_p * s_p_sq_r)) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s]
476
+ neg_cent4 = torch.sum(-0.5 * (m_p ** 2) * s_p_sq_r, [1], keepdim=True) # [b, 1, t_s]
477
+ neg_cent = neg_cent1 + neg_cent2 + neg_cent3 + neg_cent4
478
+
479
+ attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)
480
+ attn = monotonic_align.maximum_path(neg_cent, attn_mask.squeeze(1)).unsqueeze(1).detach()
481
+
482
+ w = attn.sum(2)
483
+ if self.use_sdp:
484
+ l_length = self.dp(x, x_mask, w, g=g)
485
+ l_length = l_length / torch.sum(x_mask)
486
+ else:
487
+ logw_ = torch.log(w + 1e-6) * x_mask
488
+ logw = self.dp(x, x_mask, g=g)
489
+ l_length = torch.sum((logw - logw_)**2, [1,2]) / torch.sum(x_mask) # for averaging
490
+
491
+ # expand prior
492
+ m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(1, 2)
493
+ logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(1, 2)
494
+
495
+ z_slice, ids_slice = commons.rand_slice_segments(z, y_lengths, self.segment_size)
496
+ o = self.dec(z_slice, g=g)
497
+ return o, l_length, attn, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q)
498
+
499
+ def infer(self, x, x_lengths, sid=None, noise_scale=1, length_scale=1, noise_scale_w=1., max_len=None):
500
+ x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths)
501
+ if self.n_speakers > 0:
502
+ g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
503
+ else:
504
+ g = None
505
+
506
+ if self.use_sdp:
507
+ logw = self.dp(x, x_mask, g=g, reverse=True, noise_scale=noise_scale_w)
508
+ else:
509
+ logw = self.dp(x, x_mask, g=g)
510
+ w = torch.exp(logw) * x_mask * length_scale
511
+ w_ceil = torch.ceil(w)
512
+ y_lengths = torch.clamp_min(torch.sum(w_ceil, [1, 2]), 1).long()
513
+ y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, None), 1).to(x_mask.dtype)
514
+ attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)
515
+ attn = commons.generate_path(w_ceil, attn_mask)
516
+
517
+ m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(1, 2) # [b, t', t], [b, t, d] -> [b, d, t']
518
+ logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(1, 2) # [b, t', t], [b, t, d] -> [b, d, t']
519
+
520
+ z_p = m_p + torch.randn_like(m_p) * torch.exp(logs_p) * noise_scale
521
+ z = self.flow(z_p, y_mask, g=g, reverse=True)
522
+ o = self.dec((z * y_mask)[:,:,:max_len], g=g)
523
+ return o, attn, y_mask, (z, z_p, m_p, logs_p)
524
+
525
+ def voice_conversion(self, y, y_lengths, sid_src, sid_tgt):
526
+ assert self.n_speakers > 0, "n_speakers have to be larger than 0."
527
+ g_src = self.emb_g(sid_src).unsqueeze(-1)
528
+ g_tgt = self.emb_g(sid_tgt).unsqueeze(-1)
529
+ z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g_src)
530
+ z_p = self.flow(z, y_mask, g=g_src)
531
+ z_hat = self.flow(z_p, y_mask, g=g_tgt, reverse=True)
532
+ o_hat = self.dec(z_hat * y_mask, g=g_tgt)
533
+ return o_hat, y_mask, (z, z_p, z_hat)