-
Notifications
You must be signed in to change notification settings - Fork 4
/
models.py
2625 lines (2247 loc) · 111 KB
/
models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import torch.nn as nn
from diffusion.diffusion_utils import calc_diffusion_step_embedding
#from diffusion.diffusion_multinomial import MultinomialDiffusion
from diffusion.diffusion_model import F0_Diffusion
from diffusion.diffusers_modules import Downsample1D, Upsample1D, ResBlock1D, OutConv1DBlock
from attentions import Decoder as CrossAttn
from attentions import Encoder as SelfAttn
import commons, modules, attentions, math, torch, copy, logging
import math
from commons import generate_path
from tqdm import tqdm
import torch
import torch.nn as nn
from collections import OrderedDict
#from vdecoder.hifigan.models import Generator # from so-vits-svc
from torch.nn.utils import weight_norm, spectral_norm
from torch.nn import Conv1d, Conv2d
from commons import get_padding
from commons import convert_logdur_to_intdur
import copy
from sifigan.models.generator import SiFiGANGenerator
from singDB_loader import get_g2p_dict_from_tabledata
import monotonic_align
class VITS2_based_SiFiTTS(nn.Module):
"""
Synthesizer for Training
"""
def __init__(self,
hps,
n_vocab,
spec_channels,
segment_size,
inter_channels,
hidden_channels,
filter_channels,
n_heads,
n_layers,
kernel_size,
p_dropout,
resblock,
resblock_kernel_sizes,
resblock_dilation_sizes,
upsample_rates,
upsample_initial_channel,
upsample_kernel_sizes,
n_speakers,
gin_channels,
**kwargs):
super().__init__()
self.n_vocab = n_vocab
self.spec_channels = spec_channels
self.inter_channels = inter_channels
self.hidden_channels = hidden_channels
self.filter_channels = filter_channels
self.n_heads = n_heads
self.n_layers = n_layers
self.kernel_size = kernel_size
self.p_dropout = p_dropout
self.resblock = resblock
self.resblock_kernel_sizes = resblock_kernel_sizes
self.resblock_dilation_sizes = resblock_dilation_sizes
self.upsample_rates = upsample_rates
self.upsample_initial_channel = upsample_initial_channel
self.upsample_kernel_sizes = upsample_kernel_sizes
self.segment_size = segment_size
self.n_speakers = hps["common"]["n_speaker"]
self.gin_channels = hps["common"]["gin_channels"]
self.transformer_flow_type = "fft" # "fft" / "mono_layer" / "pre_conv" ### When mono_layer and pre_conv, kl div loss went negative.
self.current_mas_noise_scale = float(hps["VITS2_config"]["mas_noise_scale"])
self.enc_gin_channels = gin_channels
# VITS2 Text Encoder
self.enc_p = TextEncoder_VITS2(n_vocab,hps["note_encoder"]["n_note"]+1,
inter_channels,
hidden_channels,
filter_channels,
n_heads,
n_layers,
kernel_size,
p_dropout,
gin_channels=self.enc_gin_channels)
# SiFi Decoder
self.dec = SiFiGANGenerator(**hps["SiFiGANGenerator"])
self.upsample_scales= hps["SiFiGANGenerator"]["upsample_scales"]
# VITS1 Encoder
self.enc_q = PosteriorEncoder(spec_channels, inter_channels, hidden_channels, 5, 1, 16, gin_channels=gin_channels)
# VITS2 Flow
self.flow = ResidualCouplingTransformersBlock(
inter_channels,
hidden_channels,
5,
1,
4,
gin_channels=gin_channels,
use_transformer_flows=True,
transformer_flow_type=self.transformer_flow_type
)
# FastSpeech2 DurationPredictor
self.dp = VariancePredictor(hps=hps,
input_size =hps["dur_predictor"]["input_size"],
filter_size =hps["dur_predictor"]["filter_size"],
kernel =hps["dur_predictor"]["kernel_size"],
conv_output_size=hps["dur_predictor"]["filter_size"],
dropout =hps["dur_predictor"]["dropout"],
n_speaker=hps["common"]["n_speaker"])
if n_speakers >= 1:
self.emb_g = nn.Embedding(n_speakers, gin_channels)
self.ms_per_frame = hps["sampling_rate"] / (hps["hop_length"] * 1000)
self.hop_length = hps["hop_length"]
self.oto2lab, self.ph_to_id, self.id_to_ph, _,_ = get_g2p_dict_from_tabledata(table_path=hps["oto2lab_path"],
include_converter=True)
try:
self.ph_statistics = torch.load(hps["ph_statistics_path"]) #{ph:[mean,var]}
print(f"[INFO] Loaded :", hps["ph_statistics_path"])
except:
self.ph_statistics = False
def forward(self,
spec, spec_lengths,
ph_IDs, ph_IDs_lengths,
dfs,
sinewave,
speakerID):
if self.n_speakers > 0:
g = self.emb_g(speakerID).unsqueeze(-1) # [B, hidden, 1]
else:
g = None
# posterior encoder
z_spec, z_spec_m_q, z_spec_logs_q, spec_mask = self.enc_q(spec, spec_lengths.float(), g=g) # z_spec=[B, hidden, spec_len]
# Flow
z_spec_text = self.flow(z_spec, spec_mask, g=g) # z_spec_text=[B, hidden, spec_len]
# prior encoder
H_ph, H_ph_m_p, H_ph_logs_p, H_ph_mask = self.enc_p(ph_IDs, ph_IDs_lengths,
w_dur_ms=None,
ph_w_idx=None,
g=g) # H_ph=[B, hidden, ph_len]
with torch.no_grad():
# negative cross-entropy
s_p_sq_r = torch.exp(-2 * H_ph_logs_p) # [b, d, t]
neg_cent1 = torch.sum(-0.5 * math.log(2 * math.pi) - H_ph_logs_p, [1], keepdim=True) # [b, 1, t_s]
neg_cent2 = torch.matmul(-0.5 * (z_spec_text ** 2).transpose(1, 2), s_p_sq_r) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s]
neg_cent3 = torch.matmul(z_spec_text.transpose(1, 2), (H_ph_m_p * s_p_sq_r)) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s]
neg_cent4 = torch.sum(-0.5 * (H_ph_m_p ** 2) * s_p_sq_r, [1], keepdim=True) # [b, 1, t_s]
neg_cent = neg_cent1 + neg_cent2 + neg_cent3 + neg_cent4
epsilon = torch.std(neg_cent) * torch.randn_like(neg_cent) * self.current_mas_noise_scale
neg_cent = neg_cent + epsilon
attn_mask = torch.unsqueeze(H_ph_mask, 2) * torch.unsqueeze(spec_mask, -1)
attn = monotonic_align.maximum_path(neg_cent, attn_mask.squeeze(1)).unsqueeze(1).detach() # pathが出来れば誤差伝播カット
ph_dur = attn.sum(2)
# duration predict
logw_ = torch.log(ph_dur + 1e-6) * H_ph_mask
logw = self.dp(H_ph, H_ph_mask, g=g) # Note Normalization
l2_dur_loss = torch.sum((logw - logw_)**2) / torch.sum(H_ph_mask) # phoneme dur loss
dp_H_ph = H_ph # for dur discriminator H_ph=[B, hidden, ph_len]
dp_H_ph_mask = H_ph_mask
# path between ph and spec
spec_mask = torch.unsqueeze(commons.sequence_mask(spec_lengths, spec.size(2)), 1).to(spec.dtype) # [B, 1, spec_len]
attn_mask = torch.unsqueeze(H_ph_mask, 2) * torch.unsqueeze(spec_mask, -1) # attn_mask = [B, 1, ph_len, note(word)_len]
attn_gt = generate_path(duration=torch.unsqueeze(ph_dur,dim=1), mask=attn_mask)
attn_gt = torch.squeeze(attn_gt, dim=1).permute(0,2,1).float() # attn=[Batch, note_len,]
# expand prior(from ph_len to spec_len) [B, hidden, spec_len]
H_ph_mask = torch.matmul(H_ph_mask, attn_gt )
H_ph = torch.matmul(H_ph, attn_gt ) * spec_mask
H_ph_m_p = torch.matmul(H_ph_m_p , attn_gt ) * spec_mask
H_ph_logs_p = torch.matmul(H_ph_logs_p, attn_gt) * spec_mask
# slice process
z_slice, sinewave_slice, ids_slice = commons.rand_slice_segments_with_sinewave(x=z_spec,
pitch=torch.squeeze(sinewave, dim=1), # ここをSineWaveへ
x_lengths=z_spec.size(2),
hop_size= self.hop_length,
segment_size=self.segment_size) # frame level
dfs_slice = commons.dfs_slice_segment(dfs=dfs,
ids_str=copy.deepcopy(ids_slice),
upscales=self.upsample_scales,
segment_size=self.segment_size) # frame level
# SiFi Decoder
voice, excitation = self.dec(x=sinewave_slice.cuda(),
c=z_slice,
d=tuple([d.to("cuda:0") for d in dfs_slice]),
g=g)
return voice, excitation, l2_dur_loss, attn_gt, ids_slice, dp_H_ph_mask, spec_mask, \
(z_spec, z_spec_text, H_ph_m_p, H_ph_logs_p, z_spec_m_q, z_spec_logs_q), \
(dp_H_ph, logw, logw_)
# batch 1 only
def eval_infer(self, ph_IDs, ph_IDs_lengths,
speakerID,
dfs,
sinewave,
f0_lengths,
noise_scale=1,
length_scale=1,
noise_scale_w=1.):
if self.n_speakers > 0:
g = self.emb_g(speakerID).unsqueeze(-1) # [b, h, 1]
else:
g = None
# text
H_ph, H_ph_m_p, H_ph_logs_p, H_ph_mask = self.enc_p(ph_IDs, ph_IDs_lengths,
w_dur_ms=None,
ph_w_idx=None,
g=g) # H_ph=[B, hidden, ph_len]
logw = self.dp(H_ph, H_ph_mask, g=g) # Note Normalization
w = torch.exp(logw) * H_ph_mask * length_scale
w = (w/torch.sum(w)) * f0_lengths # length regurator
w_ceil = torch.ceil(w)
w_sum = torch.sum(w_ceil,dim=2).view(-1)
if w_sum != f0_lengths:
w_ceil[:,:,-1] -= w_sum - f0_lengths
y_lengths = torch.clamp_min(torch.sum(w_ceil, [1, 2]), 1).long()
y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, None), 1).to(H_ph_mask.dtype)
attn_mask = torch.unsqueeze(H_ph_mask, 2) * torch.unsqueeze(y_mask, -1)
attn = commons.generate_path(w_ceil, attn_mask).squeeze(1).permute(0,2,1)
# expand prior(from ph_len to spec_len) [B, hidden, spec_len]
H_ph_mask = torch.matmul(H_ph_mask , attn)
H_ph_m_p = torch.matmul(H_ph_m_p , attn) * H_ph_mask
H_ph_logs_p = torch.matmul(H_ph_logs_p, attn) * H_ph_mask
z_spec_text = H_ph_m_p + torch.randn_like(H_ph_m_p) * torch.exp(H_ph_logs_p) * noise_scale
z_spec = self.flow(z_spec_text, y_mask, g=g, reverse=True)
# SiFi Decoder
voice, _ = self.dec(x=sinewave.cuda(),
c=z_spec,
d=tuple([d.to("cuda:0") for d in dfs]),
g=g)
return voice, attn, y_mask
def get_mas_output(self,
spec, spec_lengths,
ph_IDs, ph_IDs_lengths,
speakerID):
if self.n_speakers > 0:
g = self.emb_g(speakerID).unsqueeze(-1) # [B, hidden, 1]
else:
g = None
# posterior encoder
z_spec, _, _, spec_mask = self.enc_q(spec, spec_lengths.float(), g=g) # z_spec=[B, hidden, spec_len]
# Flow
z_spec_text = self.flow(z_spec, spec_mask, g=g) # z_spec_text=[B, hidden, spec_len]
# prior encoder
_, H_ph_m_p, H_ph_logs_p, H_ph_mask = self.enc_p(ph_IDs, ph_IDs_lengths,
w_dur_ms=None,
ph_w_idx=None,
g=g) # H_ph=[B, hidden, ph_len]
with torch.no_grad():
# negative cross-entropy
s_p_sq_r = torch.exp(-2 * H_ph_logs_p) # [b, d, t]
neg_cent1 = torch.sum(-0.5 * math.log(2 * math.pi) - H_ph_logs_p, [1], keepdim=True) # [b, 1, t_s]
neg_cent2 = torch.matmul(-0.5 * (z_spec_text ** 2).transpose(1, 2), s_p_sq_r) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s]
neg_cent3 = torch.matmul(z_spec_text.transpose(1, 2), (H_ph_m_p * s_p_sq_r)) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s]
neg_cent4 = torch.sum(-0.5 * (H_ph_m_p ** 2) * s_p_sq_r, [1], keepdim=True) # [b, 1, t_s]
neg_cent = neg_cent1 + neg_cent2 + neg_cent3 + neg_cent4
epsilon = torch.std(neg_cent) * torch.randn_like(neg_cent) * self.current_mas_noise_scale
neg_cent = neg_cent + epsilon
attn_mask = torch.unsqueeze(H_ph_mask, 2) * torch.unsqueeze(spec_mask, -1)
attn = monotonic_align.maximum_path(neg_cent, attn_mask.squeeze(1)).unsqueeze(1).detach() # pathが出来れば誤差伝播カット
ph_dur = attn.sum(2)
return ph_dur, attn
def voice_conversion(self, y, y_lengths, sid_src, sid_tgt):
assert self.n_speakers > 0, "n_speakers have to be larger than 0."
g_src = self.emb_g(sid_src).unsqueeze(-1)
g_tgt = self.emb_g(sid_tgt).unsqueeze(-1)
z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g_src)
z_p = self.flow(z, y_mask, g=g_src)
z_hat = self.flow(z_p, y_mask, g=g_tgt, reverse=True)
o_hat = self.dec(z_hat * y_mask, g=g_tgt)
return o_hat, y_mask, (z, z_p, z_hat)
# inference only and batch size=1 only
def adjust_duration(self, ph_ids, ph_dur_pd, word_dur, n_ph_in_word, noise_scale=0.33):
ph_ids = ph_ids[0, :]
ph_dur_pd = ph_dur_pd[0][0]
word_dur = word_dur[0]
n_ph_in_word=n_ph_in_word[0]
sum_duration = torch.sum(word_dur)
total_diff = 0
out_ph_dur = torch.zeros_like(ph_dur_pd) # for duration output
ph_idx = len(ph_dur_pd)
for idx in reversed(range(len(word_dur))):
n_ph = n_ph_in_word[idx]
# first
if idx == len(word_dur)-1:
out_ph_dur[-1] = word_dur[idx]
ph_idx -= 1
# other
else:
target_ph_dur = ph_dur_pd[int(ph_idx-(1+z_n_ph)):int(ph_idx)] # Vowels this time + previous consonants
adjusted_pd_dur = torch.ceil( (target_ph_dur/torch.sum(target_ph_dur) ) * word_dur[idx])
if torch.sum(adjusted_pd_dur) != word_dur[idx]:
undur = torch.sum(adjusted_pd_dur) - word_dur[idx]
adjusted_pd_dur[0] = adjusted_pd_dur[0] - undur
out_ph_dur[int(ph_idx-(1+z_n_ph)):int(ph_idx)] = adjusted_pd_dur
ph_idx -= 1+z_n_ph
z_n_ph = n_ph - 1
# last consonants
if z_n_ph != 0:
out_ph_dur[0:z_n_ph] = ph_dur_pd[0:z_n_ph] # Vowels this time + previous consonants
#assert torch.sum(out_ph_dur) == sum_duration # check duration
# adjust ph duration by statistics
if self.ph_statistics is not False:
diff = 0
for idx in reversed(range(len(ph_ids))):
ph = self.id_to_ph[int(ph_ids[idx]-1)] # minus 1 is for mask
# fix ph_dur and calc diff
if ph in self.ph_statistics:
dur = out_ph_dur[idx]
mean_ms = torch.tensor(self.ph_statistics[ph][0]).float().cuda()
std_ms = torch.tensor(self.ph_statistics[ph][1]).float().cuda()
corr_ms = mean_ms + std_ms*torch.randn_like(mean_ms)*noise_scale
corr_dur = torch.ceil(self.ms_per_frame*corr_ms)
diff += dur - corr_dur
out_ph_dur[idx] = corr_dur
# shifting diff
else:
out_ph_dur[idx] += diff
diff=0
# shifting diff last (Perhaps not necessary)
#if diff != 0:
# out_ph_dur[0] += diff
if z_n_ph != 0:
out_ph_dur[0:z_n_ph] = ph_dur_pd[0:z_n_ph] # Vowels this time + previous consonants
#out_ph_dur[-1] -= diff # 長さ補正はconcatでやる
#assert torch.sum(out_ph_dur) == sum_duration # check duration
# 最後に子音があれば、それだけずらす。
if int(z_n_ph) == 0:
total_diff = 0
else:
total_diff = int(torch.sum(out_ph_dur[0:int(z_n_ph)]))
return out_ph_dur.view(1,1,-1), total_diff
def encode_and_dp(self,
ph_IDs, ph_IDs_lengths,
speakerID,
word_frame_dur, word_frame_dur_lenngths,
word_dur_ms, ph_word_flag,
n_ph_pool,
noise_scale=1,
length_scale=1,
get_mas_output=False):
if self.n_speakers > 0:
g = self.emb_g(speakerID).unsqueeze(-1) # [b, h, 1]
else:
g = None
# path between ph and word
word_mask = torch.unsqueeze(commons.sequence_mask(word_frame_dur_lenngths, word_frame_dur.size(1)), 1).to(word_frame_dur.dtype) # [B, 1, spec_len]
ph_IDs_mask = torch.unsqueeze(commons.sequence_mask(ph_IDs_lengths, ph_IDs.size(1)), 1).to(ph_IDs.dtype) # [B, 1, ph_len]
attn_mask = torch.unsqueeze(word_mask, 2) * torch.unsqueeze(ph_IDs_mask, -1) # attn_mask = [B, 1, ph_len, note(word)_len]
attn_ph_word= generate_path(duration=torch.unsqueeze(n_ph_pool,dim=1), mask=attn_mask)
attn_ph_word= torch.squeeze(attn_ph_word, dim=1).float() # attn=[Batch, note_len,]
word_dur_ms= torch.matmul(attn_ph_word, word_dur_ms.unsqueeze(2).float()).squeeze(2)
# text
H_ph, H_ph_m_p, H_ph_logs_p, H_ph_mask = self.enc_p(ph_IDs, ph_IDs_lengths,
w_dur_ms=word_dur_ms,
ph_w_idx=ph_word_flag,
g=g) # H_ph=[B, hidden, ph_len]
logw = self.dp(H_ph, H_ph_mask, g=g)
w = torch.exp(logw) * H_ph_mask * length_scale
w_ceil = torch.ceil(w)
w_ceil, diff = self.adjust_duration(ph_IDs, w_ceil, word_frame_dur, n_ph_pool)
y_lengths = torch.clamp_min(torch.sum(w_ceil, [1, 2]), 1).long()
y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, None), 1).to(H_ph_mask.dtype)
attn_mask = torch.unsqueeze(H_ph_mask, 2) * torch.unsqueeze(y_mask, -1)
attn = commons.generate_path(w_ceil, attn_mask).squeeze(1).permute(0,2,1)
# expand prior(from ph_len to spec_len) [B, hidden, spec_len]
H_ph_mask = torch.matmul(H_ph_mask , attn)
H_ph_m_p = torch.matmul(H_ph_m_p , attn) * H_ph_mask
H_ph_logs_p = torch.matmul(H_ph_logs_p, attn) * H_ph_mask
z_spec_text = H_ph_m_p + torch.randn_like(H_ph_m_p) * torch.exp(H_ph_logs_p) * noise_scale
z_spec = self.flow(z_spec_text, y_mask, g=g, reverse=True)
return z_spec, attn, w_ceil, g, int(diff)
def synthesize(self,sinewave, z_spec, dfs, g):
# SiFi Decoder
voice, _ = self.dec(x=sinewave.cuda(),
c=z_spec,
d=tuple([d.to("cuda:0") for d in dfs]),
g=g)
return voice
class VITS2_based_SiFiSinger(nn.Module):
"""
Synthesizer for Training
"""
def __init__(self,
hps,
n_vocab,
spec_channels,
segment_size,
inter_channels,
hidden_channels,
filter_channels,
n_heads,
n_layers,
kernel_size,
p_dropout,
resblock,
resblock_kernel_sizes,
resblock_dilation_sizes,
upsample_rates,
upsample_initial_channel,
upsample_kernel_sizes,
n_speakers,
gin_channels,
use_sdp=False,
**kwargs):
super().__init__()
self.n_vocab = n_vocab
self.spec_channels = spec_channels
self.inter_channels = inter_channels
self.hidden_channels = hidden_channels
self.filter_channels = filter_channels
self.n_heads = n_heads
self.n_layers = n_layers
self.kernel_size = kernel_size
self.p_dropout = p_dropout
self.resblock = resblock
self.resblock_kernel_sizes = resblock_kernel_sizes
self.resblock_dilation_sizes = resblock_dilation_sizes
self.upsample_rates = upsample_rates
self.upsample_initial_channel = upsample_initial_channel
self.upsample_kernel_sizes = upsample_kernel_sizes
self.segment_size = segment_size
self.n_speakers = hps["common"]["n_speaker"]
self.gin_channels = hps["common"]["gin_channels"]
self.transformer_flow_type = "fft" # "fft" / "mono_layer" / "pre_conv" ### When mono_layer and pre_conv, kl div loss went negative.
self.current_mas_noise_scale = float(hps["VITS2_config"]["mas_noise_scale"])
self.enc_gin_channels = gin_channels
# VITS2 Text Encoder (Speaker Embedding)
self.enc_p = TextEncoder_VITS2(n_vocab,hps["note_encoder"]["n_note"]+1,
inter_channels,
hidden_channels,
filter_channels,
n_heads,
n_layers,
kernel_size,
p_dropout,
gin_channels=self.enc_gin_channels)
# SiFi Decoder
self.dec = SiFiGANGenerator(**hps["SiFiGANGenerator"])
self.upsample_scales= hps["SiFiGANGenerator"]["upsample_scales"]
# VITS1 Encoder
self.enc_q = PosteriorEncoder(spec_channels, inter_channels, hidden_channels, 5, 1, 16, gin_channels=gin_channels)
# VITS2 Flow
self.flow = ResidualCouplingTransformersBlock(
inter_channels,
hidden_channels,
5,
1,
4,
gin_channels=gin_channels,
use_transformer_flows=True, # Trueにすると、kl_divergense がマイナスになる。
transformer_flow_type=self.transformer_flow_type
)
# FastSpeech2 DurationPredictor
self.dp = VariancePredictor(hps=hps,
input_size =hps["dur_predictor"]["input_size"],
filter_size =hps["dur_predictor"]["filter_size"],
kernel =hps["dur_predictor"]["kernel_size"],
conv_output_size=hps["dur_predictor"]["filter_size"],
dropout =hps["dur_predictor"]["dropout"],
n_speaker=hps["common"]["n_speaker"])
if n_speakers >= 1:
self.emb_g = nn.Embedding(n_speakers, gin_channels)
self.ms_per_frame = hps["sampling_rate"] / (hps["hop_length"] * 1000)
self.hop_length = hps["hop_length"]
self.oto2lab, self.ph_to_id, self.id_to_ph, _,_ = get_g2p_dict_from_tabledata(table_path=hps["oto2lab_path"],
include_converter=True)
try:
self.ph_statistics = torch.load(hps["ph_statistics_path"]) #{ph:[mean,var]}
print(f"[INFO] Loaded :", hps["ph_statistics_path"])
except:
self.ph_statistics = False
def forward(self,
spec, spec_lengths,
ph_IDs, ph_IDs_lengths,
ph_dur,
word_frame_dur, word_frame_dur_lenngths,
word_dur_ms, ph_word_flag,
n_ph_pool,
dfs,
sinewave,
speakerID):
if self.n_speakers > 0:
g = self.emb_g(speakerID).unsqueeze(-1) # [B, hidden, 1]
else:
g = None
# generate path between ph and word
word_mask = torch.unsqueeze(commons.sequence_mask(word_frame_dur_lenngths, word_frame_dur.size(1)), 1).to(word_frame_dur.dtype) # [B, 1, spec_len]
ph_IDs_mask = torch.unsqueeze(commons.sequence_mask(ph_IDs_lengths, ph_IDs.size(1)), 1).to(ph_IDs.dtype) # [B, 1, ph_len]
attn_mask = torch.unsqueeze(word_mask, 2) * torch.unsqueeze(ph_IDs_mask, -1) # attn_mask = [B, 1, ph_len, note(word)_len]
attn_ph_word= generate_path(duration=torch.unsqueeze(n_ph_pool,dim=1), mask=attn_mask)
attn_ph_word= torch.squeeze(attn_ph_word, dim=1).float() # attn=[Batch, note_len,]
# expand
word_dur_ms= torch.matmul(attn_ph_word, word_dur_ms.unsqueeze(2).float()).squeeze(2)
# posterior encoder
z_spec, z_spec_m_q, z_spec_logs_q, spec_mask = self.enc_q(spec, spec_lengths.float(), g=g) # z_spec=[B, hidden, spec_len]
# Flow
z_spec_text = self.flow(z_spec, spec_mask, g=g) # z_spec_text=[B, hidden, spec_len]
# prior encoder
H_ph, H_ph_m_p, H_ph_logs_p, H_ph_mask = self.enc_p(ph_IDs, ph_IDs_lengths,
w_dur_ms=word_dur_ms,
ph_w_idx=ph_word_flag,
g=g) # H_ph=[B, hidden, ph_len]
# duration predict
logw_ = torch.log(torch.unsqueeze(ph_dur,dim=1) + 1e-6) * ph_IDs_mask
logw = self.dp(H_ph, ph_IDs_mask, g=g) # Note Normalization
l2_ph_dur_loss = torch.sum((logw - logw_)**2) / torch.sum(ph_IDs_mask) # phoneme dur loss
l2_word_dur_loss = torch.sum((torch.matmul(logw, attn_ph_word) - torch.matmul(logw_, attn_ph_word))**2) / torch.sum(ph_IDs_mask) # word dur loss
l2_full_dur_loss = (torch.sum(logw_) - torch.sum(logw) )**2 / torch.sum(ph_IDs_mask) # lengths dur loss
l2_dur_loss = [l2_ph_dur_loss, l2_word_dur_loss, l2_full_dur_loss]
dp_H_ph = H_ph # for dur discriminator H_ph=[B, hidden, ph_len]
# path between ph and spec
spec_mask = torch.unsqueeze(commons.sequence_mask(spec_lengths, spec.size(2)), 1).to(spec.dtype) # [B, 1, spec_len]
ph_IDs_mask = torch.unsqueeze(commons.sequence_mask(ph_IDs_lengths, ph_IDs.size(1)), 1).to(ph_IDs.dtype) # [B, 1, ph_len]
attn_mask = torch.unsqueeze(ph_IDs_mask, 2) * torch.unsqueeze(spec_mask, -1) # attn_mask = [B, 1, ph_len, note(word)_len]
attn_gt = generate_path(duration=torch.unsqueeze(ph_dur,dim=1), mask=attn_mask)
attn_gt = torch.squeeze(attn_gt, dim=1).permute(0,2,1).float() # attn=[Batch, note_len,]
# expand prior(from ph_len to spec_len) [B, hidden, spec_len]
H_ph_mask = torch.matmul(H_ph_mask, attn_gt )
H_ph = torch.matmul(H_ph, attn_gt ) * spec_mask
H_ph_m_p = torch.matmul(H_ph_m_p , attn_gt ) * spec_mask
H_ph_logs_p = torch.matmul(H_ph_logs_p, attn_gt) * spec_mask
# slice process
z_slice, sinewave_slice, ids_slice = commons.rand_slice_segments_with_sinewave(x=z_spec,
pitch=torch.squeeze(sinewave, dim=1), # ここをSineWaveへ
x_lengths=z_spec.size(2),
hop_size= self.hop_length,
segment_size=self.segment_size) # frame level
dfs_slice = commons.dfs_slice_segment(dfs=dfs,
ids_str=copy.deepcopy(ids_slice),
upscales=self.upsample_scales,
segment_size=self.segment_size) # frame level
# SiFi Decoder
voice, excitation = self.dec(x=sinewave_slice.cuda(),
c=z_slice,
d=tuple([d.to("cuda:0") for d in dfs_slice]),
g=g)
return voice, excitation, l2_dur_loss, attn_gt, ids_slice, ph_IDs_mask, spec_mask, \
(z_spec, z_spec_text, H_ph_m_p, H_ph_logs_p, z_spec_m_q, z_spec_logs_q), \
(dp_H_ph, logw, logw_)
# batch 1 only
def eval_infer(self, ph_IDs, ph_IDs_lengths,
speakerID,
word_frame_dur, word_frame_dur_lenngths,
word_dur_ms, ph_word_flag,
n_ph_pool,
dfs,
sinewave,
noise_scale=1,
length_scale=1,
noise_scale_w=1.):
if self.n_speakers > 0:
g = self.emb_g(speakerID).unsqueeze(-1) # [b, h, 1]
else:
g = None
# path between ph and word
word_mask = torch.unsqueeze(commons.sequence_mask(word_frame_dur_lenngths, word_frame_dur.size(1)), 1).to(word_frame_dur.dtype) # [B, 1, spec_len]
ph_IDs_mask = torch.unsqueeze(commons.sequence_mask(ph_IDs_lengths, ph_IDs.size(1)), 1).to(ph_IDs.dtype) # [B, 1, ph_len]
attn_mask = torch.unsqueeze(word_mask, 2) * torch.unsqueeze(ph_IDs_mask, -1) # attn_mask = [B, 1, ph_len, note(word)_len]
attn_ph_word= generate_path(duration=torch.unsqueeze(n_ph_pool,dim=1), mask=attn_mask)
attn_ph_word= torch.squeeze(attn_ph_word, dim=1).float() # attn=[Batch, note_len,]
word_dur_ms= torch.matmul(attn_ph_word, word_dur_ms.unsqueeze(2).float()).squeeze(2)
# text
H_ph, H_ph_m_p, H_ph_logs_p, H_ph_mask = self.enc_p(ph_IDs, ph_IDs_lengths,
w_dur_ms=word_dur_ms,
ph_w_idx=ph_word_flag,
g=g) # H_ph=[B, hidden, ph_len]
logw = self.dp(H_ph, H_ph_mask, g=g) # Note Normalization
w = torch.exp(logw) * H_ph_mask * length_scale
w_ceil = torch.ceil(w)
w_ceil, diff = self.adjust_duration(ph_IDs, w_ceil, word_frame_dur, n_ph_pool)
w_ceil[0,0,-1] -= diff # eval時だとph分余分なframeが作られるので、末尾でつじつま合わせ。
y_lengths = torch.clamp_min(torch.sum(w_ceil, [1, 2]), 1).long()
y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, None), 1).to(H_ph_mask.dtype)
attn_mask = torch.unsqueeze(H_ph_mask, 2) * torch.unsqueeze(y_mask, -1)
attn = commons.generate_path(w_ceil, attn_mask).squeeze(1).permute(0,2,1)
# expand prior(from ph_len to spec_len) [B, hidden, spec_len]
H_ph_mask = torch.matmul(H_ph_mask , attn)
H_ph_m_p = torch.matmul(H_ph_m_p , attn) * H_ph_mask
H_ph_logs_p = torch.matmul(H_ph_logs_p, attn) * H_ph_mask
z_spec_text = H_ph_m_p + torch.randn_like(H_ph_m_p) * torch.exp(H_ph_logs_p) * noise_scale
z_spec = self.flow(z_spec_text, y_mask, g=g, reverse=True)
# SiFi Decoder
voice, _ = self.dec(x=sinewave.cuda(),
c=z_spec,
d=tuple([d.to("cuda:0") for d in dfs]),
g=g)
return voice, attn, y_mask
def voice_conversion(self, y, y_lengths, sid_src, sid_tgt):
assert self.n_speakers > 0, "n_speakers have to be larger than 0."
g_src = self.emb_g(sid_src).unsqueeze(-1)
g_tgt = self.emb_g(sid_tgt).unsqueeze(-1)
z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g_src)
z_p = self.flow(z, y_mask, g=g_src)
z_hat = self.flow(z_p, y_mask, g=g_tgt, reverse=True)
o_hat = self.dec(z_hat * y_mask, g=g_tgt)
return o_hat, y_mask, (z, z_p, z_hat)
# inference only and batch size=1 only
def adjust_duration(self, ph_ids, ph_dur_pd, word_dur, n_ph_in_word, noise_scale=0.33):
ph_ids = ph_ids[0, :]
ph_dur_pd = ph_dur_pd[0][0]
word_dur = word_dur[0]
n_ph_in_word=n_ph_in_word[0]
sum_duration = torch.sum(word_dur)
total_diff = 0
out_ph_dur = torch.zeros_like(ph_dur_pd) # for duration output
ph_idx = len(ph_dur_pd)
for idx in reversed(range(len(word_dur))):
n_ph = n_ph_in_word[idx]
# first
if idx == len(word_dur)-1:
out_ph_dur[-1] = word_dur[idx]
ph_idx -= 1
# other
else:
target_ph_dur = ph_dur_pd[int(ph_idx-(1+z_n_ph)):int(ph_idx)] # Vowels this time + previous consonants
adjusted_pd_dur = torch.ceil( (target_ph_dur/torch.sum(target_ph_dur) ) * word_dur[idx])
if torch.sum(adjusted_pd_dur) != word_dur[idx]:
undur = torch.sum(adjusted_pd_dur) - word_dur[idx]
adjusted_pd_dur[0] = adjusted_pd_dur[0] - undur
out_ph_dur[int(ph_idx-(1+z_n_ph)):int(ph_idx)] = adjusted_pd_dur
ph_idx -= 1+z_n_ph
z_n_ph = n_ph - 1
# last consonants
if z_n_ph != 0:
out_ph_dur[0:z_n_ph] = ph_dur_pd[0:z_n_ph] # Vowels this time + previous consonants
#assert torch.sum(out_ph_dur) == sum_duration # check duration
# adjust ph duration by statistics
if self.ph_statistics is not False:
diff = 0
for idx in reversed(range(len(ph_ids))):
ph = self.id_to_ph[int(ph_ids[idx]-1)] # minus 1 is for mask
# fix ph_dur and calc diff
if ph in self.ph_statistics:
dur = out_ph_dur[idx]
mean_ms = torch.tensor(self.ph_statistics[ph][0]).float().cuda()
std_ms = torch.tensor(self.ph_statistics[ph][1]).float().cuda()
corr_ms = mean_ms + std_ms*torch.randn_like(mean_ms)*noise_scale
corr_dur = torch.ceil(self.ms_per_frame*corr_ms)
diff += dur - corr_dur
out_ph_dur[idx] = corr_dur
# shifting diff
else:
out_ph_dur[idx] += diff
diff=0
# shifting diff last (Perhaps not necessary)
#if diff != 0:
# out_ph_dur[0] += diff
if z_n_ph != 0:
out_ph_dur[0:z_n_ph] = ph_dur_pd[0:z_n_ph] # Vowels this time + previous consonants
#out_ph_dur[-1] -= diff # 長さ補正はconcatでやる
#assert torch.sum(out_ph_dur) == sum_duration # check duration
# 最後に子音があれば、それだけずらす。
if int(z_n_ph) == 0:
total_diff = 0
else:
total_diff = int(torch.sum(out_ph_dur[0:int(z_n_ph)]))
return out_ph_dur.view(1,1,-1), total_diff
def encode_and_dp(self,
ph_IDs, ph_IDs_lengths,
speakerID,
word_frame_dur, word_frame_dur_lenngths,
word_dur_ms, ph_word_flag,
n_ph_pool,
noise_scale=1,
length_scale=1):
if self.n_speakers > 0:
g = self.emb_g(speakerID).unsqueeze(-1) # [b, h, 1]
else:
g = None
# path between ph and word
word_mask = torch.unsqueeze(commons.sequence_mask(word_frame_dur_lenngths, word_frame_dur.size(1)), 1).to(word_frame_dur.dtype) # [B, 1, spec_len]
ph_IDs_mask = torch.unsqueeze(commons.sequence_mask(ph_IDs_lengths, ph_IDs.size(1)), 1).to(ph_IDs.dtype) # [B, 1, ph_len]
attn_mask = torch.unsqueeze(word_mask, 2) * torch.unsqueeze(ph_IDs_mask, -1) # attn_mask = [B, 1, ph_len, note(word)_len]
attn_ph_word= generate_path(duration=torch.unsqueeze(n_ph_pool,dim=1), mask=attn_mask)
attn_ph_word= torch.squeeze(attn_ph_word, dim=1).float() # attn=[Batch, note_len,]
word_dur_ms= torch.matmul(attn_ph_word, word_dur_ms.unsqueeze(2).float()).squeeze(2)
# text
H_ph, H_ph_m_p, H_ph_logs_p, H_ph_mask = self.enc_p(ph_IDs, ph_IDs_lengths,
w_dur_ms=word_dur_ms,
ph_w_idx=ph_word_flag,
g=g) # H_ph=[B, hidden, ph_len]
logw = self.dp(H_ph, H_ph_mask, g=g)
w = torch.exp(logw) * H_ph_mask * length_scale
w_ceil = torch.ceil(w)
w_ceil, diff = self.adjust_duration(ph_IDs, w_ceil, word_frame_dur, n_ph_pool)
y_lengths = torch.clamp_min(torch.sum(w_ceil, [1, 2]), 1).long()
y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, None), 1).to(H_ph_mask.dtype)
attn_mask = torch.unsqueeze(H_ph_mask, 2) * torch.unsqueeze(y_mask, -1)
attn = commons.generate_path(w_ceil, attn_mask).squeeze(1).permute(0,2,1)
# expand prior(from ph_len to spec_len) [B, hidden, spec_len]
H_ph_mask = torch.matmul(H_ph_mask , attn)
H_ph_m_p = torch.matmul(H_ph_m_p , attn) * H_ph_mask
H_ph_logs_p = torch.matmul(H_ph_logs_p, attn) * H_ph_mask
z_spec_text = H_ph_m_p + torch.randn_like(H_ph_m_p) * torch.exp(H_ph_logs_p) * noise_scale
z_spec = self.flow(z_spec_text, y_mask, g=g, reverse=True)
return z_spec, attn, w_ceil, g, int(diff)
def synthesize(self,sinewave, z_spec, dfs, g):
# SiFi Decoder
voice, _ = self.dec(x=sinewave.cuda(),
c=z_spec,
d=tuple([d.to("cuda:0") for d in dfs]),
g=g)
return voice
class Rezero(torch.nn.Module):
def __init__(self):
super(Rezero, self).__init__()
self.alpha = torch.nn.Parameter(torch.zeros(size=(1,)))
def forward(self, x):
return self.alpha * x
class StochasticDurationPredictor(nn.Module):
def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, n_flows=4, gin_channels=0):
super().__init__()
filter_channels = in_channels # it needs to be removed from future version.
self.in_channels = in_channels
self.filter_channels = filter_channels
self.kernel_size = kernel_size
self.p_dropout = p_dropout
self.n_flows = n_flows
self.gin_channels = gin_channels
self.log_flow = modules.Log()
self.flows = nn.ModuleList()
self.flows.append(modules.ElementwiseAffine(2))
for i in range(n_flows):
self.flows.append(modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3))
self.flows.append(modules.Flip())
self.post_pre = nn.Conv1d(1, filter_channels, 1)
self.post_proj = nn.Conv1d(filter_channels, filter_channels, 1)
self.post_convs = modules.DDSConv(filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout)
self.post_flows = nn.ModuleList()
self.post_flows.append(modules.ElementwiseAffine(2))
for i in range(4):
self.post_flows.append(modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3))
self.post_flows.append(modules.Flip())
self.pre = nn.Conv1d(in_channels, filter_channels, 1)
self.proj = nn.Conv1d(filter_channels, filter_channels, 1)
self.convs = modules.DDSConv(filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout)
if gin_channels != 0:
self.cond = nn.Conv1d(gin_channels, filter_channels, 1)
def forward(self, x, x_mask, w=None, g=None, reverse=False, noise_scale=1.0):
x = torch.detach(x)
x = self.pre(x)
if g is not None:
g = torch.detach(g)
x = x + self.cond(g)
x = self.convs(x, x_mask)
x = self.proj(x) * x_mask
if not reverse:
flows = self.flows
assert w is not None
logdet_tot_q = 0
h_w = self.post_pre(w)
h_w = self.post_convs(h_w, x_mask)
h_w = self.post_proj(h_w) * x_mask
e_q = torch.randn(w.size(0), 2, w.size(2)).to(device=x.device, dtype=x.dtype) * x_mask
z_q = e_q
for flow in self.post_flows:
z_q, logdet_q = flow(z_q, x_mask, g=(x + h_w))
logdet_tot_q += logdet_q
z_u, z1 = torch.split(z_q, [1, 1], 1)
u = torch.sigmoid(z_u) * x_mask
z0 = (w - u) * x_mask
logdet_tot_q += torch.sum((nn.functional.logsigmoid(z_u) + nn.functional.logsigmoid(-z_u)) * x_mask, [1,2])
logq = torch.sum(-0.5 * (math.log(2*math.pi) + (e_q**2)) * x_mask, [1,2]) - logdet_tot_q
logdet_tot = 0
z0, logdet = self.log_flow(z0, x_mask)
logdet_tot += logdet
z = torch.cat([z0, z1], 1)
for flow in flows:
z, logdet = flow(z, x_mask, g=x, reverse=reverse)
logdet_tot = logdet_tot + logdet
nll = torch.sum(0.5 * (math.log(2*math.pi) + (z**2)) * x_mask, [1,2]) - logdet_tot
return nll + logq # [b]
else:
flows = list(reversed(self.flows))
flows = flows[:-2] + [flows[-1]] # remove a useless vflow
z = torch.randn(x.size(0), 2, x.size(2)).to(device=x.device, dtype=x.dtype) * noise_scale
for flow in flows:
z = flow(z, x_mask, g=x, reverse=reverse)
z0, z1 = torch.split(z, [1, 1], 1)
logw = z0
return logw
class DurationPredictor(nn.Module):
def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, gin_channels=0):
super().__init__()
self.in_channels = in_channels
self.filter_channels = filter_channels
self.kernel_size = kernel_size
self.p_dropout = p_dropout
self.gin_channels = gin_channels
self.drop = nn.Dropout(p_dropout)
self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size, padding=kernel_size//2)
self.norm_1 = modules.LayerNorm(filter_channels)
self.conv_2 = nn.Conv1d(filter_channels, filter_channels, kernel_size, padding=kernel_size//2)
self.norm_2 = modules.LayerNorm(filter_channels)
self.proj = nn.Conv1d(filter_channels, 1, 1)
if gin_channels != 0:
self.cond = nn.Conv1d(gin_channels, in_channels, 1)
def forward(self, x, x_mask, g=None):
x = torch.detach(x)
if g is not None:
g = torch.detach(g)
x = x + self.cond(g)
x = self.conv_1(x * x_mask)
x = torch.relu(x)
x = self.norm_1(x)
x = self.drop(x)
x = self.conv_2(x * x_mask)
x = torch.relu(x)
x = self.norm_2(x)
x = self.drop(x)
x = self.proj(x * x_mask)
return x * x_mask
class DurationDiscriminator(nn.Module): #vits2
# TODO : not using "spk conditioning" for now according to the paper.
# Can be a better discriminator if we use it.
def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, gin_channels=0):
super().__init__()
self.in_channels = in_channels
self.filter_channels = filter_channels
self.kernel_size = kernel_size
self.p_dropout = p_dropout
self.gin_channels = gin_channels
self.drop = nn.Dropout(p_dropout)
self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size, padding=kernel_size//2)
# self.norm_1 = modules.LayerNorm(filter_channels)
self.conv_2 = nn.Conv1d(filter_channels, filter_channels, kernel_size, padding=kernel_size//2)
# self.norm_2 = modules.LayerNorm(filter_channels)
self.dur_proj = nn.Conv1d(1, filter_channels, 1)
self.pre_out_conv_1 = nn.Conv1d(2*filter_channels, filter_channels, kernel_size, padding=kernel_size//2)
self.pre_out_norm_1 = modules.LayerNorm(filter_channels)
self.pre_out_conv_2 = nn.Conv1d(filter_channels, filter_channels, kernel_size, padding=kernel_size//2)
self.pre_out_norm_2 = modules.LayerNorm(filter_channels)
# if gin_channels != 0:
# self.cond = nn.Conv1d(gin_channels, in_channels, 1)
self.output_layer = nn.Sequential(
nn.Linear(filter_channels, 1),
nn.Sigmoid()
)
def forward_probability(self, x, x_mask, dur, g=None):
dur = self.dur_proj(dur)
x = torch.cat([x, dur], dim=1)
x = self.pre_out_conv_1(x * x_mask)
# x = torch.relu(x)
# x = self.pre_out_norm_1(x)
# x = self.drop(x)
x = self.pre_out_conv_2(x * x_mask)
# x = torch.relu(x)
# x = self.pre_out_norm_2(x)
# x = self.drop(x)
x = x * x_mask
x = x.transpose(1, 2)
output_prob = self.output_layer(x)
return output_prob
# x=hidden_input, dur=dur
def forward(self, x, x_mask, dur_r, dur_hat, g=None):
x = torch.detach(x)
# if g is not None:
# g = torch.detach(g)
# x = x + self.cond(g)
x = self.conv_1(x * x_mask)
# x = torch.relu(x)
# x = self.norm_1(x)
# x = self.drop(x)
x = self.conv_2(x * x_mask)
# x = torch.relu(x)