uptaleend Plachta commited on
Commit
031e87b
0 Parent(s):

Duplicate from Plachta/VITS-Umamusume-voice-synthesizer

Browse files

Co-authored-by: ElderFrog <[email protected]>

This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +34 -0
  2. ONNXVITS_infer.py +201 -0
  3. ONNXVITS_inference.py +36 -0
  4. ONNXVITS_models.py +509 -0
  5. ONNXVITS_modules.py +390 -0
  6. ONNXVITS_to_onnx.py +31 -0
  7. ONNXVITS_transforms.py +196 -0
  8. ONNXVITS_utils.py +19 -0
  9. ONNX_net/G_jp/dec.onnx +3 -0
  10. ONNX_net/G_jp/dp.onnx +3 -0
  11. ONNX_net/G_jp/enc_p.onnx +3 -0
  12. ONNX_net/G_jp/flow.onnx +3 -0
  13. ONNX_net/G_trilingual/dec.onnx +3 -0
  14. ONNX_net/G_trilingual/dp.onnx +3 -0
  15. ONNX_net/G_trilingual/enc_p.onnx +3 -0
  16. ONNX_net/G_trilingual/flow.onnx +3 -0
  17. README.md +13 -0
  18. app.py +256 -0
  19. attentions.py +300 -0
  20. commons.py +97 -0
  21. configs/uma87.json +133 -0
  22. configs/uma_trilingual.json +202 -0
  23. data_utils.py +393 -0
  24. hubert_model.py +221 -0
  25. jieba/dict.txt +0 -0
  26. losses.py +61 -0
  27. mel_processing.py +101 -0
  28. models.py +542 -0
  29. modules.py +387 -0
  30. monotonic_align/__init__.py +19 -0
  31. monotonic_align/__pycache__/__init__.cpython-37.pyc +0 -0
  32. monotonic_align/build/lib.win-amd64-cpython-37/monotonic_align/core.cp37-win_amd64.pyd +0 -0
  33. monotonic_align/build/temp.win-amd64-cpython-37/Release/core.cp37-win_amd64.exp +0 -0
  34. monotonic_align/build/temp.win-amd64-cpython-37/Release/core.cp37-win_amd64.lib +0 -0
  35. monotonic_align/build/temp.win-amd64-cpython-37/Release/core.obj +0 -0
  36. monotonic_align/core.c +0 -0
  37. monotonic_align/core.pyx +42 -0
  38. monotonic_align/monotonic_align/core.cp37-win_amd64.pyd +0 -0
  39. monotonic_align/setup.py +9 -0
  40. pretrained_models/D_trilingual.pth +3 -0
  41. pretrained_models/G_jp.pth +3 -0
  42. pretrained_models/G_trilingual.pth +3 -0
  43. requirements.txt +28 -0
  44. text/LICENSE +19 -0
  45. text/__init__.py +32 -0
  46. text/__pycache__/__init__.cpython-37.pyc +0 -0
  47. text/__pycache__/cleaners.cpython-37.pyc +0 -0
  48. text/__pycache__/english.cpython-37.pyc +0 -0
  49. text/__pycache__/japanese.cpython-37.pyc +0 -0
  50. text/__pycache__/korean.cpython-37.pyc +0 -0
.gitattributes ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
ONNXVITS_infer.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import commons
3
+ import models
4
+
5
+ import math
6
+ from torch import nn
7
+ from torch.nn import functional as F
8
+
9
+ import modules
10
+ import attentions
11
+
12
+ from torch.nn import Conv1d, ConvTranspose1d, 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 TextEncoder(nn.Module):
18
+ def __init__(self,
19
+ n_vocab,
20
+ out_channels,
21
+ hidden_channels,
22
+ filter_channels,
23
+ n_heads,
24
+ n_layers,
25
+ kernel_size,
26
+ p_dropout,
27
+ emotion_embedding):
28
+ super().__init__()
29
+ self.n_vocab = n_vocab
30
+ self.out_channels = out_channels
31
+ self.hidden_channels = hidden_channels
32
+ self.filter_channels = filter_channels
33
+ self.n_heads = n_heads
34
+ self.n_layers = n_layers
35
+ self.kernel_size = kernel_size
36
+ self.p_dropout = p_dropout
37
+ self.emotion_embedding = emotion_embedding
38
+
39
+ if self.n_vocab != 0:
40
+ self.emb = nn.Embedding(n_vocab, hidden_channels)
41
+ if emotion_embedding:
42
+ self.emo_proj = nn.Linear(1024, hidden_channels)
43
+ nn.init.normal_(self.emb.weight, 0.0, hidden_channels ** -0.5)
44
+
45
+ self.encoder = attentions.Encoder(
46
+ hidden_channels,
47
+ filter_channels,
48
+ n_heads,
49
+ n_layers,
50
+ kernel_size,
51
+ p_dropout)
52
+ self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
53
+
54
+ def forward(self, x, x_lengths, emotion_embedding=None):
55
+ if self.n_vocab != 0:
56
+ x = self.emb(x) * math.sqrt(self.hidden_channels) # [b, t, h]
57
+ if emotion_embedding is not None:
58
+ print("emotion added")
59
+ x = x + self.emo_proj(emotion_embedding.unsqueeze(1))
60
+ x = torch.transpose(x, 1, -1) # [b, h, t]
61
+ x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
62
+
63
+ x = self.encoder(x * x_mask, x_mask)
64
+ stats = self.proj(x) * x_mask
65
+
66
+ m, logs = torch.split(stats, self.out_channels, dim=1)
67
+ return x, m, logs, x_mask
68
+
69
+
70
+ class PosteriorEncoder(nn.Module):
71
+ def __init__(self,
72
+ in_channels,
73
+ out_channels,
74
+ hidden_channels,
75
+ kernel_size,
76
+ dilation_rate,
77
+ n_layers,
78
+ gin_channels=0):
79
+ super().__init__()
80
+ self.in_channels = in_channels
81
+ self.out_channels = out_channels
82
+ self.hidden_channels = hidden_channels
83
+ self.kernel_size = kernel_size
84
+ self.dilation_rate = dilation_rate
85
+ self.n_layers = n_layers
86
+ self.gin_channels = gin_channels
87
+
88
+ self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
89
+ self.enc = modules.WN(hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels)
90
+ self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
91
+
92
+ def forward(self, x, x_lengths, g=None):
93
+ x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
94
+ x = self.pre(x) * x_mask
95
+ x = self.enc(x, x_mask, g=g)
96
+ stats = self.proj(x) * x_mask
97
+ m, logs = torch.split(stats, self.out_channels, dim=1)
98
+ z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask
99
+ return z, m, logs, x_mask
100
+
101
+
102
+ class SynthesizerTrn(models.SynthesizerTrn):
103
+ """
104
+ Synthesizer for Training
105
+ """
106
+
107
+ def __init__(self,
108
+ n_vocab,
109
+ spec_channels,
110
+ segment_size,
111
+ inter_channels,
112
+ hidden_channels,
113
+ filter_channels,
114
+ n_heads,
115
+ n_layers,
116
+ kernel_size,
117
+ p_dropout,
118
+ resblock,
119
+ resblock_kernel_sizes,
120
+ resblock_dilation_sizes,
121
+ upsample_rates,
122
+ upsample_initial_channel,
123
+ upsample_kernel_sizes,
124
+ n_speakers=0,
125
+ gin_channels=0,
126
+ use_sdp=True,
127
+ emotion_embedding=False,
128
+ ONNX_dir="./ONNX_net/",
129
+ **kwargs):
130
+
131
+ super().__init__(
132
+ n_vocab,
133
+ spec_channels,
134
+ segment_size,
135
+ inter_channels,
136
+ hidden_channels,
137
+ filter_channels,
138
+ n_heads,
139
+ n_layers,
140
+ kernel_size,
141
+ p_dropout,
142
+ resblock,
143
+ resblock_kernel_sizes,
144
+ resblock_dilation_sizes,
145
+ upsample_rates,
146
+ upsample_initial_channel,
147
+ upsample_kernel_sizes,
148
+ n_speakers=n_speakers,
149
+ gin_channels=gin_channels,
150
+ use_sdp=use_sdp,
151
+ **kwargs
152
+ )
153
+ self.ONNX_dir = ONNX_dir
154
+ self.enc_p = TextEncoder(n_vocab,
155
+ inter_channels,
156
+ hidden_channels,
157
+ filter_channels,
158
+ n_heads,
159
+ n_layers,
160
+ kernel_size,
161
+ p_dropout,
162
+ emotion_embedding)
163
+ self.enc_q = PosteriorEncoder(spec_channels, inter_channels, hidden_channels, 5, 1, 16, gin_channels=gin_channels)
164
+
165
+ def infer(self, x, x_lengths, sid=None, noise_scale=1, length_scale=1, noise_scale_w=1., max_len=None,
166
+ emotion_embedding=None):
167
+ from ONNXVITS_utils import runonnx
168
+ with torch.no_grad():
169
+ x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths, emotion_embedding)
170
+
171
+ if self.n_speakers > 0:
172
+ g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
173
+ else:
174
+ g = None
175
+
176
+ # logw = self.dp(x, x_mask, g=g, reverse=True, noise_scale=noise_scale_w)
177
+ logw = runonnx(f"{self.ONNX_dir}dp.onnx", x=x.numpy(), x_mask=x_mask.numpy(), g=g.numpy())
178
+ logw = torch.from_numpy(logw[0])
179
+
180
+ w = torch.exp(logw) * x_mask * length_scale
181
+ w_ceil = torch.ceil(w)
182
+ y_lengths = torch.clamp_min(torch.sum(w_ceil, [1, 2]), 1).long()
183
+ y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, None), 1).to(x_mask.dtype)
184
+ attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)
185
+ attn = commons.generate_path(w_ceil, attn_mask)
186
+
187
+ m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(1, 2) # [b, t', t], [b, t, d] -> [b, d, t']
188
+ logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(1,
189
+ 2) # [b, t', t], [b, t, d] -> [b, d, t']
190
+
191
+ z_p = m_p + torch.randn_like(m_p) * torch.exp(logs_p) * noise_scale
192
+
193
+ # z = self.flow(z_p, y_mask, g=g, reverse=True)
194
+ z = runonnx(f"{self.ONNX_dir}flow.onnx", z_p=z_p.numpy(), y_mask=y_mask.numpy(), g=g.numpy())
195
+ z = torch.from_numpy(z[0])
196
+
197
+ # o = self.dec((z * y_mask)[:,:,:max_len], g=g)
198
+ o = runonnx(f"{self.ONNX_dir}dec.onnx", z_in=(z * y_mask)[:, :, :max_len].numpy(), g=g.numpy())
199
+ o = torch.from_numpy(o[0])
200
+
201
+ return o, attn, y_mask, (z, z_p, m_p, logs_p)
ONNXVITS_inference.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ logging.getLogger('numba').setLevel(logging.WARNING)
3
+ import IPython.display as ipd
4
+ import torch
5
+ import commons
6
+ import utils
7
+ import ONNXVITS_infer
8
+ from text import text_to_sequence
9
+
10
+ def get_text(text, hps):
11
+ text_norm = text_to_sequence(text, hps.symbols, hps.data.text_cleaners)
12
+ if hps.data.add_blank:
13
+ text_norm = commons.intersperse(text_norm, 0)
14
+ text_norm = torch.LongTensor(text_norm)
15
+ return text_norm
16
+
17
+ hps = utils.get_hparams_from_file("../vits/pretrained_models/uma87.json")
18
+
19
+ net_g = ONNXVITS_infer.SynthesizerTrn(
20
+ len(hps.symbols),
21
+ hps.data.filter_length // 2 + 1,
22
+ hps.train.segment_size // hps.data.hop_length,
23
+ n_speakers=hps.data.n_speakers,
24
+ **hps.model)
25
+ _ = net_g.eval()
26
+
27
+ _ = utils.load_checkpoint("../vits/pretrained_models/uma_1153000.pth", net_g)
28
+
29
+ text1 = get_text("おはようございます。", hps)
30
+ stn_tst = text1
31
+ with torch.no_grad():
32
+ x_tst = stn_tst.unsqueeze(0)
33
+ x_tst_lengths = torch.LongTensor([stn_tst.size(0)])
34
+ sid = torch.LongTensor([0])
35
+ audio = net_g.infer(x_tst, x_tst_lengths, sid=sid, noise_scale=.667, noise_scale_w=0.8, length_scale=1)[0][0,0].data.cpu().float().numpy()
36
+ print(audio)
ONNXVITS_models.py ADDED
@@ -0,0 +1,509 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ONNXVITS_modules as 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
+ self.w = None
51
+ self.reverse = None
52
+ self.noise_scale = None
53
+ def forward(self, x, x_mask, g=None):
54
+ w = self.w
55
+ reverse = self.reverse
56
+ noise_scale = self.noise_scale
57
+
58
+ x = torch.detach(x)
59
+ x = self.pre(x)
60
+ if g is not None:
61
+ g = torch.detach(g)
62
+ x = x + self.cond(g)
63
+ x = self.convs(x, x_mask)
64
+ x = self.proj(x) * x_mask
65
+
66
+ if not reverse:
67
+ flows = self.flows
68
+ assert w is not None
69
+
70
+ logdet_tot_q = 0
71
+ h_w = self.post_pre(w)
72
+ h_w = self.post_convs(h_w, x_mask)
73
+ h_w = self.post_proj(h_w) * x_mask
74
+ e_q = torch.randn(w.size(0), 2, w.size(2)).to(device=x.device, dtype=x.dtype) * x_mask
75
+ z_q = e_q
76
+ for flow in self.post_flows:
77
+ z_q, logdet_q = flow(z_q, x_mask, g=(x + h_w))
78
+ logdet_tot_q += logdet_q
79
+ z_u, z1 = torch.split(z_q, [1, 1], 1)
80
+ u = torch.sigmoid(z_u) * x_mask
81
+ z0 = (w - u) * x_mask
82
+ logdet_tot_q += torch.sum((F.logsigmoid(z_u) + F.logsigmoid(-z_u)) * x_mask, [1,2])
83
+ logq = torch.sum(-0.5 * (math.log(2*math.pi) + (e_q**2)) * x_mask, [1,2]) - logdet_tot_q
84
+
85
+ logdet_tot = 0
86
+ z0, logdet = self.log_flow(z0, x_mask)
87
+ logdet_tot += logdet
88
+ z = torch.cat([z0, z1], 1)
89
+ for flow in flows:
90
+ z, logdet = flow(z, x_mask, g=x, reverse=reverse)
91
+ logdet_tot = logdet_tot + logdet
92
+ nll = torch.sum(0.5 * (math.log(2*math.pi) + (z**2)) * x_mask, [1,2]) - logdet_tot
93
+ return nll + logq # [b]
94
+ else:
95
+ flows = list(reversed(self.flows))
96
+ flows = flows[:-2] + [flows[-1]] # remove a useless vflow
97
+ z = torch.randn(x.size(0), 2, x.size(2)).to(device=x.device, dtype=x.dtype) * noise_scale
98
+ for flow in flows:
99
+ z = flow(z, x_mask, g=x, reverse=reverse)
100
+ z0, z1 = torch.split(z, [1, 1], 1)
101
+ logw = z0
102
+ return logw
103
+
104
+
105
+ class TextEncoder(nn.Module):
106
+ def __init__(self,
107
+ n_vocab,
108
+ out_channels,
109
+ hidden_channels,
110
+ filter_channels,
111
+ n_heads,
112
+ n_layers,
113
+ kernel_size,
114
+ p_dropout):
115
+ super().__init__()
116
+ self.n_vocab = n_vocab
117
+ self.out_channels = out_channels
118
+ self.hidden_channels = hidden_channels
119
+ self.filter_channels = filter_channels
120
+ self.n_heads = n_heads
121
+ self.n_layers = n_layers
122
+ self.kernel_size = kernel_size
123
+ self.p_dropout = p_dropout
124
+
125
+ self.emb = nn.Embedding(n_vocab, hidden_channels)
126
+ nn.init.normal_(self.emb.weight, 0.0, hidden_channels**-0.5)
127
+
128
+ self.encoder = attentions.Encoder(
129
+ hidden_channels,
130
+ filter_channels,
131
+ n_heads,
132
+ n_layers,
133
+ kernel_size,
134
+ p_dropout)
135
+ self.proj= nn.Conv1d(hidden_channels, out_channels * 2, 1)
136
+
137
+ def forward(self, x, x_lengths):
138
+ x = self.emb(x) * math.sqrt(self.hidden_channels) # [b, t, h]
139
+ x = torch.transpose(x, 1, -1) # [b, h, t]
140
+ x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
141
+
142
+ x = self.encoder(x * x_mask, x_mask)
143
+ stats = self.proj(x) * x_mask
144
+
145
+ m, logs = torch.split(stats, self.out_channels, dim=1)
146
+ return x, m, logs, x_mask
147
+
148
+
149
+ class ResidualCouplingBlock(nn.Module):
150
+ def __init__(self,
151
+ channels,
152
+ hidden_channels,
153
+ kernel_size,
154
+ dilation_rate,
155
+ n_layers,
156
+ n_flows=4,
157
+ gin_channels=0):
158
+ super().__init__()
159
+ self.channels = channels
160
+ self.hidden_channels = hidden_channels
161
+ self.kernel_size = kernel_size
162
+ self.dilation_rate = dilation_rate
163
+ self.n_layers = n_layers
164
+ self.n_flows = n_flows
165
+ self.gin_channels = gin_channels
166
+
167
+ self.flows = nn.ModuleList()
168
+ for i in range(n_flows):
169
+ self.flows.append(modules.ResidualCouplingLayer(channels, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels, mean_only=True))
170
+ self.flows.append(modules.Flip())
171
+
172
+ self.reverse = None
173
+ def forward(self, x, x_mask, g=None):
174
+ reverse = self.reverse
175
+ if not reverse:
176
+ for flow in self.flows:
177
+ x, _ = flow(x, x_mask, g=g, reverse=reverse)
178
+ else:
179
+ for flow in reversed(self.flows):
180
+ x = flow(x, x_mask, g=g, reverse=reverse)
181
+ return x
182
+
183
+
184
+ class PosteriorEncoder(nn.Module):
185
+ def __init__(self,
186
+ in_channels,
187
+ out_channels,
188
+ hidden_channels,
189
+ kernel_size,
190
+ dilation_rate,
191
+ n_layers,
192
+ gin_channels=0):
193
+ super().__init__()
194
+ self.in_channels = in_channels
195
+ self.out_channels = out_channels
196
+ self.hidden_channels = hidden_channels
197
+ self.kernel_size = kernel_size
198
+ self.dilation_rate = dilation_rate
199
+ self.n_layers = n_layers
200
+ self.gin_channels = gin_channels
201
+
202
+ self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
203
+ self.enc = modules.WN(hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels)
204
+ self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
205
+
206
+ def forward(self, x, x_lengths, g=None):
207
+ x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
208
+ x = self.pre(x) * x_mask # x_in : [b, c, t] -> [b, h, t]
209
+ x = self.enc(x, x_mask, g=g) # x_in : [b, h, t], g : [b, h, 1], x = x_in + g
210
+ stats = self.proj(x) * x_mask
211
+ m, logs = torch.split(stats, self.out_channels, dim=1)
212
+ z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask
213
+ return z, m, logs, x_mask # z, m, logs : [b, h, t]
214
+
215
+
216
+ class Generator(torch.nn.Module):
217
+ def __init__(self, initial_channel, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, upsample_initial_channel, upsample_kernel_sizes, gin_channels=0):
218
+ super(Generator, self).__init__()
219
+ self.num_kernels = len(resblock_kernel_sizes)
220
+ self.num_upsamples = len(upsample_rates)
221
+ self.conv_pre = Conv1d(initial_channel, upsample_initial_channel, 7, 1, padding=3)
222
+ resblock = modules.ResBlock1 if resblock == '1' else modules.ResBlock2
223
+
224
+ self.ups = nn.ModuleList()
225
+ for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
226
+ self.ups.append(weight_norm(
227
+ ConvTranspose1d(upsample_initial_channel//(2**i), upsample_initial_channel//(2**(i+1)),
228
+ k, u, padding=(k-u)//2)))
229
+
230
+ self.resblocks = nn.ModuleList()
231
+ for i in range(len(self.ups)):
232
+ ch = upsample_initial_channel//(2**(i+1))
233
+ for j, (k, d) in enumerate(zip(resblock_kernel_sizes, resblock_dilation_sizes)):
234
+ self.resblocks.append(resblock(ch, k, d))
235
+
236
+ self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False)
237
+ self.ups.apply(init_weights)
238
+
239
+ if gin_channels != 0:
240
+ self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
241
+
242
+ def forward(self, x, g=None):
243
+ x = self.conv_pre(x)
244
+ if g is not None:
245
+ x = x + self.cond(g)
246
+
247
+ for i in range(self.num_upsamples):
248
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
249
+ x = self.ups[i](x)
250
+ xs = None
251
+ for j in range(self.num_kernels):
252
+ if xs is None:
253
+ xs = self.resblocks[i*self.num_kernels+j](x)
254
+ else:
255
+ xs += self.resblocks[i*self.num_kernels+j](x)
256
+ x = xs / self.num_kernels
257
+ x = F.leaky_relu(x)
258
+ x = self.conv_post(x)
259
+ x = torch.tanh(x)
260
+
261
+ return x
262
+
263
+ def remove_weight_norm(self):
264
+ print('Removing weight norm...')
265
+ for l in self.ups:
266
+ remove_weight_norm(l)
267
+ for l in self.resblocks:
268
+ l.remove_weight_norm()
269
+
270
+
271
+ class DiscriminatorP(torch.nn.Module):
272
+ def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False):
273
+ super(DiscriminatorP, self).__init__()
274
+ self.period = period
275
+ self.use_spectral_norm = use_spectral_norm
276
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
277
+ self.convs = nn.ModuleList([
278
+ norm_f(Conv2d(1, 32, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
279
+ norm_f(Conv2d(32, 128, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
280
+ norm_f(Conv2d(128, 512, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
281
+ norm_f(Conv2d(512, 1024, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
282
+ norm_f(Conv2d(1024, 1024, (kernel_size, 1), 1, padding=(get_padding(kernel_size, 1), 0))),
283
+ ])
284
+ self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
285
+
286
+ def forward(self, x):
287
+ fmap = []
288
+
289
+ # 1d to 2d
290
+ b, c, t = x.shape
291
+ if t % self.period != 0: # pad first
292
+ n_pad = self.period - (t % self.period)
293
+ x = F.pad(x, (0, n_pad), "reflect")
294
+ t = t + n_pad
295
+ x = x.view(b, c, t // self.period, self.period)
296
+
297
+ for l in self.convs:
298
+ x = l(x)
299
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
300
+ fmap.append(x)
301
+ x = self.conv_post(x)
302
+ fmap.append(x)
303
+ x = torch.flatten(x, 1, -1)
304
+
305
+ return x, fmap
306
+
307
+
308
+ class DiscriminatorS(torch.nn.Module):
309
+ def __init__(self, use_spectral_norm=False):
310
+ super(DiscriminatorS, self).__init__()
311
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
312
+ self.convs = nn.ModuleList([
313
+ norm_f(Conv1d(1, 16, 15, 1, padding=7)),
314
+ norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)),
315
+ norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)),
316
+ norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)),
317
+ norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)),
318
+ norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
319
+ ])
320
+ self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
321
+
322
+ def forward(self, x):
323
+ fmap = []
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 MultiPeriodDiscriminator(torch.nn.Module):
337
+ def __init__(self, use_spectral_norm=False):
338
+ super(MultiPeriodDiscriminator, self).__init__()
339
+ periods = [2,3,5,7,11]
340
+
341
+ discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
342
+ discs = discs + [DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods]
343
+ self.discriminators = nn.ModuleList(discs)
344
+
345
+ def forward(self, y, y_hat):
346
+ y_d_rs = []
347
+ y_d_gs = []
348
+ fmap_rs = []
349
+ fmap_gs = []
350
+ for i, d in enumerate(self.discriminators):
351
+ y_d_r, fmap_r = d(y)
352
+ y_d_g, fmap_g = d(y_hat)
353
+ y_d_rs.append(y_d_r)
354
+ y_d_gs.append(y_d_g)
355
+ fmap_rs.append(fmap_r)
356
+ fmap_gs.append(fmap_g)
357
+
358
+ return y_d_rs, y_d_gs, fmap_rs, fmap_gs
359
+
360
+
361
+
362
+ class SynthesizerTrn(nn.Module):
363
+ """
364
+ Synthesizer for Training
365
+ """
366
+
367
+ def __init__(self,
368
+ n_vocab,
369
+ spec_channels,
370
+ segment_size,
371
+ inter_channels,
372
+ hidden_channels,
373
+ filter_channels,
374
+ n_heads,
375
+ n_layers,
376
+ kernel_size,
377
+ p_dropout,
378
+ resblock,
379
+ resblock_kernel_sizes,
380
+ resblock_dilation_sizes,
381
+ upsample_rates,
382
+ upsample_initial_channel,
383
+ upsample_kernel_sizes,
384
+ n_speakers=0,
385
+ gin_channels=0,
386
+ use_sdp=True,
387
+ **kwargs):
388
+
389
+ super().__init__()
390
+ self.n_vocab = n_vocab
391
+ self.spec_channels = spec_channels
392
+ self.inter_channels = inter_channels
393
+ self.hidden_channels = hidden_channels
394
+ self.filter_channels = filter_channels
395
+ self.n_heads = n_heads
396
+ self.n_layers = n_layers
397
+ self.kernel_size = kernel_size
398
+ self.p_dropout = p_dropout
399
+ self.resblock = resblock
400
+ self.resblock_kernel_sizes = resblock_kernel_sizes
401
+ self.resblock_dilation_sizes = resblock_dilation_sizes
402
+ self.upsample_rates = upsample_rates
403
+ self.upsample_initial_channel = upsample_initial_channel
404
+ self.upsample_kernel_sizes = upsample_kernel_sizes
405
+ self.segment_size = segment_size
406
+ self.n_speakers = n_speakers
407
+ self.gin_channels = gin_channels
408
+
409
+ self.use_sdp = use_sdp
410
+
411
+ self.enc_p = TextEncoder(n_vocab,
412
+ inter_channels,
413
+ hidden_channels,
414
+ filter_channels,
415
+ n_heads,
416
+ n_layers,
417
+ kernel_size,
418
+ p_dropout)
419
+ self.dec = Generator(inter_channels, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, upsample_initial_channel, upsample_kernel_sizes, gin_channels=gin_channels)
420
+ self.enc_q = PosteriorEncoder(spec_channels, inter_channels, hidden_channels, 5, 1, 16, gin_channels=gin_channels)
421
+ self.flow = ResidualCouplingBlock(inter_channels, hidden_channels, 5, 1, 4, gin_channels=gin_channels)
422
+
423
+ self.dp = StochasticDurationPredictor(hidden_channels, 192, 3, 0.5, 4, gin_channels=gin_channels)
424
+
425
+ if n_speakers > 0:
426
+ self.emb_g = nn.Embedding(n_speakers, gin_channels)
427
+
428
+ def forward(self, x, x_lengths, sid=None, noise_scale=.667, length_scale=1, noise_scale_w=.8, max_len=None):
429
+ torch.onnx.export(
430
+ self.enc_p,
431
+ (x, x_lengths),
432
+ "ONNX_net/enc_p.onnx",
433
+ input_names=["x", "x_lengths"],
434
+ output_names=["xout", "m_p", "logs_p", "x_mask"],
435
+ dynamic_axes={
436
+ "x" : [1],
437
+ "xout" : [2],
438
+ "m_p" : [2],
439
+ "logs_p" : [2],
440
+ "x_mask" : [2]
441
+ },
442
+ verbose=True,
443
+ )
444
+ x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths)
445
+
446
+ if self.n_speakers > 0:
447
+ g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
448
+ else:
449
+ g = None
450
+
451
+ self.dp.reverse = True
452
+ self.dp.noise_scale = noise_scale_w
453
+ torch.onnx.export(
454
+ self.dp,
455
+ (x, x_mask, g),
456
+ "ONNX_net/dp.onnx",
457
+ input_names=["x", "x_mask", "g"],
458
+ output_names=["logw"],
459
+ dynamic_axes={
460
+ "x" : [2],
461
+ "x_mask" : [2],
462
+ "logw" : [2]
463
+ },
464
+ verbose=True,
465
+ )
466
+ logw = self.dp(x, x_mask, g=g)
467
+ w = torch.exp(logw) * x_mask * length_scale
468
+ w_ceil = torch.ceil(w)
469
+ y_lengths = torch.clamp_min(torch.sum(w_ceil, [1, 2]), 1).long()
470
+ y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, None), 1).to(x_mask.dtype)
471
+ attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)
472
+ attn = commons.generate_path(w_ceil, attn_mask)
473
+
474
+ m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(1, 2) # [b, t', t], [b, t, d] -> [b, d, t']
475
+ logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(1, 2) # [b, t', t], [b, t, d] -> [b, d, t']
476
+
477
+ z_p = m_p + torch.randn_like(m_p) * torch.exp(logs_p) * noise_scale
478
+
479
+ self.flow.reverse = True
480
+ torch.onnx.export(
481
+ self.flow,
482
+ (z_p, y_mask, g),
483
+ "ONNX_net/flow.onnx",
484
+ input_names=["z_p", "y_mask", "g"],
485
+ output_names=["z"],
486
+ dynamic_axes={
487
+ "z_p" : [2],
488
+ "y_mask" : [2],
489
+ "z" : [2]
490
+ },
491
+ verbose=True,
492
+ )
493
+ z = self.flow(z_p, y_mask, g=g)
494
+ z_in = (z * y_mask)[:,:,:max_len]
495
+
496
+ torch.onnx.export(
497
+ self.dec,
498
+ (z_in, g),
499
+ "ONNX_net/dec.onnx",
500
+ input_names=["z_in", "g"],
501
+ output_names=["o"],
502
+ dynamic_axes={
503
+ "z_in" : [2],
504
+ "o" : [2]
505
+ },
506
+ verbose=True,
507
+ )
508
+ o = self.dec(z_in, g=g)
509
+ return o
ONNXVITS_modules.py ADDED
@@ -0,0 +1,390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import math
3
+ import numpy as np
4
+ import scipy
5
+ import torch
6
+ from torch import nn
7
+ from torch.nn import functional as F
8
+
9
+ from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
10
+ from torch.nn.utils import weight_norm, remove_weight_norm
11
+
12
+ import commons
13
+ from commons import init_weights, get_padding
14
+ from ONNXVITS_transforms import piecewise_rational_quadratic_transform
15
+
16
+
17
+ LRELU_SLOPE = 0.1
18
+
19
+
20
+ class LayerNorm(nn.Module):
21
+ def __init__(self, channels, eps=1e-5):
22
+ super().__init__()
23
+ self.channels = channels
24
+ self.eps = eps
25
+
26
+ self.gamma = nn.Parameter(torch.ones(channels))
27
+ self.beta = nn.Parameter(torch.zeros(channels))
28
+
29
+ def forward(self, x):
30
+ x = x.transpose(1, -1)
31
+ x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
32
+ return x.transpose(1, -1)
33
+
34
+
35
+ class ConvReluNorm(nn.Module):
36
+ def __init__(self, in_channels, hidden_channels, out_channels, kernel_size, n_layers, p_dropout):
37
+ super().__init__()
38
+ self.in_channels = in_channels
39
+ self.hidden_channels = hidden_channels
40
+ self.out_channels = out_channels
41
+ self.kernel_size = kernel_size
42
+ self.n_layers = n_layers
43
+ self.p_dropout = p_dropout
44
+ assert n_layers > 1, "Number of layers should be larger than 0."
45
+
46
+ self.conv_layers = nn.ModuleList()
47
+ self.norm_layers = nn.ModuleList()
48
+ self.conv_layers.append(nn.Conv1d(in_channels, hidden_channels, kernel_size, padding=kernel_size//2))
49
+ self.norm_layers.append(LayerNorm(hidden_channels))
50
+ self.relu_drop = nn.Sequential(
51
+ nn.ReLU(),
52
+ nn.Dropout(p_dropout))
53
+ for _ in range(n_layers-1):
54
+ self.conv_layers.append(nn.Conv1d(hidden_channels, hidden_channels, kernel_size, padding=kernel_size//2))
55
+ self.norm_layers.append(LayerNorm(hidden_channels))
56
+ self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
57
+ self.proj.weight.data.zero_()
58
+ self.proj.bias.data.zero_()
59
+
60
+ def forward(self, x, x_mask):
61
+ x_org = x
62
+ for i in range(self.n_layers):
63
+ x = self.conv_layers[i](x * x_mask)
64
+ x = self.norm_layers[i](x)
65
+ x = self.relu_drop(x)
66
+ x = x_org + self.proj(x)
67
+ return x * x_mask
68
+
69
+
70
+ class DDSConv(nn.Module):
71
+ """
72
+ Dialted and Depth-Separable Convolution
73
+ """
74
+ def __init__(self, channels, kernel_size, n_layers, p_dropout=0.):
75
+ super().__init__()
76
+ self.channels = channels
77
+ self.kernel_size = kernel_size
78
+ self.n_layers = n_layers
79
+ self.p_dropout = p_dropout
80
+
81
+ self.drop = nn.Dropout(p_dropout)
82
+ self.convs_sep = nn.ModuleList()
83
+ self.convs_1x1 = nn.ModuleList()
84
+ self.norms_1 = nn.ModuleList()
85
+ self.norms_2 = nn.ModuleList()
86
+ for i in range(n_layers):
87
+ dilation = kernel_size ** i
88
+ padding = (kernel_size * dilation - dilation) // 2
89
+ self.convs_sep.append(nn.Conv1d(channels, channels, kernel_size,
90
+ groups=channels, dilation=dilation, padding=padding
91
+ ))
92
+ self.convs_1x1.append(nn.Conv1d(channels, channels, 1))
93
+ self.norms_1.append(LayerNorm(channels))
94
+ self.norms_2.append(LayerNorm(channels))
95
+
96
+ def forward(self, x, x_mask, g=None):
97
+ if g is not None:
98
+ x = x + g
99
+ for i in range(self.n_layers):
100
+ y = self.convs_sep[i](x * x_mask)
101
+ y = self.norms_1[i](y)
102
+ y = F.gelu(y)
103
+ y = self.convs_1x1[i](y)
104
+ y = self.norms_2[i](y)
105
+ y = F.gelu(y)
106
+ y = self.drop(y)
107
+ x = x + y
108
+ return x * x_mask
109
+
110
+
111
+ class WN(torch.nn.Module):
112
+ def __init__(self, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=0, p_dropout=0):
113
+ super(WN, self).__init__()
114
+ assert(kernel_size % 2 == 1)
115
+ self.hidden_channels =hidden_channels
116
+ self.kernel_size = kernel_size,
117
+ self.dilation_rate = dilation_rate
118
+ self.n_layers = n_layers
119
+ self.gin_channels = gin_channels
120
+ self.p_dropout = p_dropout
121
+
122
+ self.in_layers = torch.nn.ModuleList()
123
+ self.res_skip_layers = torch.nn.ModuleList()
124
+ self.drop = nn.Dropout(p_dropout)
125
+
126
+ if gin_channels != 0:
127
+ cond_layer = torch.nn.Conv1d(gin_channels, 2*hidden_channels*n_layers, 1)
128
+ self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name='weight')
129
+
130
+ for i in range(n_layers):
131
+ dilation = dilation_rate ** i
132
+ padding = int((kernel_size * dilation - dilation) / 2)
133
+ in_layer = torch.nn.Conv1d(hidden_channels, 2*hidden_channels, kernel_size,
134
+ dilation=dilation, padding=padding)
135
+ in_layer = torch.nn.utils.weight_norm(in_layer, name='weight')
136
+ self.in_layers.append(in_layer)
137
+
138
+ # last one is not necessary
139
+ if i < n_layers - 1:
140
+ res_skip_channels = 2 * hidden_channels
141
+ else:
142
+ res_skip_channels = hidden_channels
143
+
144
+ res_skip_layer = torch.nn.Conv1d(hidden_channels, res_skip_channels, 1)
145
+ res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name='weight')
146
+ self.res_skip_layers.append(res_skip_layer)
147
+
148
+ def forward(self, x, x_mask, g=None, **kwargs):
149
+ output = torch.zeros_like(x)
150
+ n_channels_tensor = torch.IntTensor([self.hidden_channels])
151
+
152
+ if g is not None:
153
+ g = self.cond_layer(g)
154
+
155
+ for i in range(self.n_layers):
156
+ x_in = self.in_layers[i](x)
157
+ if g is not None:
158
+ cond_offset = i * 2 * self.hidden_channels
159
+ g_l = g[:,cond_offset:cond_offset+2*self.hidden_channels,:]
160
+ else:
161
+ g_l = torch.zeros_like(x_in)
162
+
163
+ acts = commons.fused_add_tanh_sigmoid_multiply(
164
+ x_in,
165
+ g_l,
166
+ n_channels_tensor)
167
+ acts = self.drop(acts)
168
+
169
+ res_skip_acts = self.res_skip_layers[i](acts)
170
+ if i < self.n_layers - 1:
171
+ res_acts = res_skip_acts[:,:self.hidden_channels,:]
172
+ x = (x + res_acts) * x_mask
173
+ output = output + res_skip_acts[:,self.hidden_channels:,:]
174
+ else:
175
+ output = output + res_skip_acts
176
+ return output * x_mask
177
+
178
+ def remove_weight_norm(self):
179
+ if self.gin_channels != 0:
180
+ torch.nn.utils.remove_weight_norm(self.cond_layer)
181
+ for l in self.in_layers:
182
+ torch.nn.utils.remove_weight_norm(l)
183
+ for l in self.res_skip_layers:
184
+ torch.nn.utils.remove_weight_norm(l)
185
+
186
+
187
+ class ResBlock1(torch.nn.Module):
188
+ def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):
189
+ super(ResBlock1, self).__init__()
190
+ self.convs1 = nn.ModuleList([
191
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
192
+ padding=get_padding(kernel_size, dilation[0]))),
193
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
194
+ padding=get_padding(kernel_size, dilation[1]))),
195
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[2],
196
+ padding=get_padding(kernel_size, dilation[2])))
197
+ ])
198
+ self.convs1.apply(init_weights)
199
+
200
+ self.convs2 = nn.ModuleList([
201
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
202
+ padding=get_padding(kernel_size, 1))),
203
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
204
+ padding=get_padding(kernel_size, 1))),
205
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
206
+ padding=get_padding(kernel_size, 1)))
207
+ ])
208
+ self.convs2.apply(init_weights)
209
+
210
+ def forward(self, x, x_mask=None):
211
+ for c1, c2 in zip(self.convs1, self.convs2):
212
+ xt = F.leaky_relu(x, LRELU_SLOPE)
213
+ if x_mask is not None:
214
+ xt = xt * x_mask
215
+ xt = c1(xt)
216
+ xt = F.leaky_relu(xt, LRELU_SLOPE)
217
+ if x_mask is not None:
218
+ xt = xt * x_mask
219
+ xt = c2(xt)
220
+ x = xt + x
221
+ if x_mask is not None:
222
+ x = x * x_mask
223
+ return x
224
+
225
+ def remove_weight_norm(self):
226
+ for l in self.convs1:
227
+ remove_weight_norm(l)
228
+ for l in self.convs2:
229
+ remove_weight_norm(l)
230
+
231
+
232
+ class ResBlock2(torch.nn.Module):
233
+ def __init__(self, channels, kernel_size=3, dilation=(1, 3)):
234
+ super(ResBlock2, self).__init__()
235
+ self.convs = nn.ModuleList([
236
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
237
+ padding=get_padding(kernel_size, dilation[0]))),
238
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
239
+ padding=get_padding(kernel_size, dilation[1])))
240
+ ])
241
+ self.convs.apply(init_weights)
242
+
243
+ def forward(self, x, x_mask=None):
244
+ for c in self.convs:
245
+ xt = F.leaky_relu(x, LRELU_SLOPE)
246
+ if x_mask is not None:
247
+ xt = xt * x_mask
248
+ xt = c(xt)
249
+ x = xt + x
250
+ if x_mask is not None:
251
+ x = x * x_mask
252
+ return x
253
+
254
+ def remove_weight_norm(self):
255
+ for l in self.convs:
256
+ remove_weight_norm(l)
257
+
258
+
259
+ class Log(nn.Module):
260
+ def forward(self, x, x_mask, reverse=False, **kwargs):
261
+ if not reverse:
262
+ y = torch.log(torch.clamp_min(x, 1e-5)) * x_mask
263
+ logdet = torch.sum(-y, [1, 2])
264
+ return y, logdet
265
+ else:
266
+ x = torch.exp(x) * x_mask
267
+ return x
268
+
269
+
270
+ class Flip(nn.Module):
271
+ def forward(self, x, *args, reverse=False, **kwargs):
272
+ x = torch.flip(x, [1])
273
+ if not reverse:
274
+ logdet = torch.zeros(x.size(0)).to(dtype=x.dtype, device=x.device)
275
+ return x, logdet
276
+ else:
277
+ return x
278
+
279
+
280
+ class ElementwiseAffine(nn.Module):
281
+ def __init__(self, channels):
282
+ super().__init__()
283
+ self.channels = channels
284
+ self.m = nn.Parameter(torch.zeros(channels,1))
285
+ self.logs = nn.Parameter(torch.zeros(channels,1))
286
+
287
+ def forward(self, x, x_mask, reverse=False, **kwargs):
288
+ if not reverse:
289
+ y = self.m + torch.exp(self.logs) * x
290
+ y = y * x_mask
291
+ logdet = torch.sum(self.logs * x_mask, [1,2])
292
+ return y, logdet
293
+ else:
294
+ x = (x - self.m) * torch.exp(-self.logs) * x_mask
295
+ return x
296
+
297
+
298
+ class ResidualCouplingLayer(nn.Module):
299
+ def __init__(self,
300
+ channels,
301
+ hidden_channels,
302
+ kernel_size,
303
+ dilation_rate,
304
+ n_layers,
305
+ p_dropout=0,
306
+ gin_channels=0,
307
+ mean_only=False):
308
+ assert channels % 2 == 0, "channels should be divisible by 2"
309
+ super().__init__()
310
+ self.channels = channels
311
+ self.hidden_channels = hidden_channels
312
+ self.kernel_size = kernel_size
313
+ self.dilation_rate = dilation_rate
314
+ self.n_layers = n_layers
315
+ self.half_channels = channels // 2
316
+ self.mean_only = mean_only
317
+
318
+ self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
319
+ self.enc = WN(hidden_channels, kernel_size, dilation_rate, n_layers, p_dropout=p_dropout, gin_channels=gin_channels)
320
+ self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
321
+ self.post.weight.data.zero_()
322
+ self.post.bias.data.zero_()
323
+
324
+ def forward(self, x, x_mask, g=None, reverse=False):
325
+ x0, x1 = torch.split(x, [self.half_channels]*2, 1)
326
+ h = self.pre(x0) * x_mask
327
+ h = self.enc(h, x_mask, g=g)
328
+ stats = self.post(h) * x_mask
329
+ if not self.mean_only:
330
+ m, logs = torch.split(stats, [self.half_channels]*2, 1)
331
+ else:
332
+ m = stats
333
+ logs = torch.zeros_like(m)
334
+
335
+ if not reverse:
336
+ x1 = m + x1 * torch.exp(logs) * x_mask
337
+ x = torch.cat([x0, x1], 1)
338
+ logdet = torch.sum(logs, [1,2])
339
+ return x, logdet
340
+ else:
341
+ x1 = (x1 - m) * torch.exp(-logs) * x_mask
342
+ x = torch.cat([x0, x1], 1)
343
+ return x
344
+
345
+
346
+ class ConvFlow(nn.Module):
347
+ def __init__(self, in_channels, filter_channels, kernel_size, n_layers, num_bins=10, tail_bound=5.0):
348
+ super().__init__()
349
+ self.in_channels = in_channels
350
+ self.filter_channels = filter_channels
351
+ self.kernel_size = kernel_size
352
+ self.n_layers = n_layers
353
+ self.num_bins = num_bins
354
+ self.tail_bound = tail_bound
355
+ self.half_channels = in_channels // 2
356
+
357
+ self.pre = nn.Conv1d(self.half_channels, filter_channels, 1)
358
+ self.convs = DDSConv(filter_channels, kernel_size, n_layers, p_dropout=0.)
359
+ self.proj = nn.Conv1d(filter_channels, self.half_channels * (num_bins * 3 - 1), 1)
360
+ self.proj.weight.data.zero_()
361
+ self.proj.bias.data.zero_()
362
+
363
+ def forward(self, x, x_mask, g=None, reverse=False):
364
+ x0, x1 = torch.split(x, [self.half_channels]*2, 1)
365
+ h = self.pre(x0)
366
+ h = self.convs(h, x_mask, g=g)
367
+ h = self.proj(h) * x_mask
368
+
369
+ b, c, t = x0.shape
370
+ h = h.reshape(b, c, -1, t).permute(0, 1, 3, 2) # [b, cx?, t] -> [b, c, t, ?]
371
+
372
+ unnormalized_widths = h[..., :self.num_bins] / math.sqrt(self.filter_channels)
373
+ unnormalized_heights = h[..., self.num_bins:2*self.num_bins] / math.sqrt(self.filter_channels)
374
+ unnormalized_derivatives = h[..., 2 * self.num_bins:]
375
+
376
+ x1, logabsdet = piecewise_rational_quadratic_transform(x1,
377
+ unnormalized_widths,
378
+ unnormalized_heights,
379
+ unnormalized_derivatives,
380
+ inverse=reverse,
381
+ tails='linear',
382
+ tail_bound=self.tail_bound
383
+ )
384
+
385
+ x = torch.cat([x0, x1], 1) * x_mask
386
+ logdet = torch.sum(logabsdet * x_mask, [1,2])
387
+ if not reverse:
388
+ return x, logdet
389
+ else:
390
+ return x
ONNXVITS_to_onnx.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ONNXVITS_models
2
+ import utils
3
+ from text import text_to_sequence
4
+ import torch
5
+ import commons
6
+
7
+ def get_text(text, hps):
8
+ text_norm = text_to_sequence(text, hps.symbols, hps.data.text_cleaners)
9
+ if hps.data.add_blank:
10
+ text_norm = commons.intersperse(text_norm, 0)
11
+ text_norm = torch.LongTensor(text_norm)
12
+ return text_norm
13
+
14
+ hps = utils.get_hparams_from_file("../vits/pretrained_models/uma87.json")
15
+ symbols = hps.symbols
16
+ net_g = ONNXVITS_models.SynthesizerTrn(
17
+ len(symbols),
18
+ hps.data.filter_length // 2 + 1,
19
+ hps.train.segment_size // hps.data.hop_length,
20
+ n_speakers=hps.data.n_speakers,
21
+ **hps.model)
22
+ _ = net_g.eval()
23
+ _ = utils.load_checkpoint("../vits/pretrained_models/uma_1153000.pth", net_g)
24
+
25
+ text1 = get_text("ありがとうございます。", hps)
26
+ stn_tst = text1
27
+ with torch.no_grad():
28
+ x_tst = stn_tst.unsqueeze(0)
29
+ x_tst_lengths = torch.LongTensor([stn_tst.size(0)])
30
+ sid = torch.tensor([0])
31
+ o = net_g(x_tst, x_tst_lengths, sid=sid, noise_scale=.667, noise_scale_w=0.8, length_scale=1)
ONNXVITS_transforms.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch.nn import functional as F
3
+
4
+ import numpy as np
5
+
6
+
7
+ DEFAULT_MIN_BIN_WIDTH = 1e-3
8
+ DEFAULT_MIN_BIN_HEIGHT = 1e-3
9
+ DEFAULT_MIN_DERIVATIVE = 1e-3
10
+
11
+
12
+ def piecewise_rational_quadratic_transform(inputs,
13
+ unnormalized_widths,
14
+ unnormalized_heights,
15
+ unnormalized_derivatives,
16
+ inverse=False,
17
+ tails=None,
18
+ tail_bound=1.,
19
+ min_bin_width=DEFAULT_MIN_BIN_WIDTH,
20
+ min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
21
+ min_derivative=DEFAULT_MIN_DERIVATIVE):
22
+
23
+ if tails is None:
24
+ spline_fn = rational_quadratic_spline
25
+ spline_kwargs = {}
26
+ else:
27
+ spline_fn = unconstrained_rational_quadratic_spline
28
+ spline_kwargs = {
29
+ 'tails': tails,
30
+ 'tail_bound': tail_bound
31
+ }
32
+
33
+ outputs, logabsdet = spline_fn(
34
+ inputs=inputs,
35
+ unnormalized_widths=unnormalized_widths,
36
+ unnormalized_heights=unnormalized_heights,
37
+ unnormalized_derivatives=unnormalized_derivatives,
38
+ inverse=inverse,
39
+ min_bin_width=min_bin_width,
40
+ min_bin_height=min_bin_height,
41
+ min_derivative=min_derivative,
42
+ **spline_kwargs
43
+ )
44
+ return outputs, logabsdet
45
+
46
+
47
+ def searchsorted(bin_locations, inputs, eps=1e-6):
48
+ bin_locations[..., -1] += eps
49
+ return torch.sum(
50
+ inputs[..., None] >= bin_locations,
51
+ dim=-1
52
+ ) - 1
53
+
54
+
55
+ def unconstrained_rational_quadratic_spline(inputs,
56
+ unnormalized_widths,
57
+ unnormalized_heights,
58
+ unnormalized_derivatives,
59
+ inverse=False,
60
+ tails='linear',
61
+ tail_bound=1.,
62
+ min_bin_width=DEFAULT_MIN_BIN_WIDTH,
63
+ min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
64
+ min_derivative=DEFAULT_MIN_DERIVATIVE):
65
+ inside_interval_mask = (inputs >= -tail_bound) & (inputs <= tail_bound)
66
+ outside_interval_mask = ~inside_interval_mask
67
+
68
+ outputs = torch.zeros_like(inputs)
69
+ logabsdet = torch.zeros_like(inputs)
70
+
71
+ if tails == 'linear':
72
+ #unnormalized_derivatives = F.pad(unnormalized_derivatives, pad=(1, 1))
73
+ unnormalized_derivatives_ = torch.zeros((1, 1, unnormalized_derivatives.size(2), unnormalized_derivatives.size(3)+2))
74
+ unnormalized_derivatives_[...,1:-1] = unnormalized_derivatives
75
+ unnormalized_derivatives = unnormalized_derivatives_
76
+ constant = np.log(np.exp(1 - min_derivative) - 1)
77
+ unnormalized_derivatives[..., 0] = constant
78
+ unnormalized_derivatives[..., -1] = constant
79
+
80
+ outputs[outside_interval_mask] = inputs[outside_interval_mask]
81
+ logabsdet[outside_interval_mask] = 0
82
+ else:
83
+ raise RuntimeError('{} tails are not implemented.'.format(tails))
84
+
85
+ outputs[inside_interval_mask], logabsdet[inside_interval_mask] = rational_quadratic_spline(
86
+ inputs=inputs[inside_interval_mask],
87
+ unnormalized_widths=unnormalized_widths[inside_interval_mask, :],
88
+ unnormalized_heights=unnormalized_heights[inside_interval_mask, :],
89
+ unnormalized_derivatives=unnormalized_derivatives[inside_interval_mask, :],
90
+ inverse=inverse,
91
+ left=-tail_bound, right=tail_bound, bottom=-tail_bound, top=tail_bound,
92
+ min_bin_width=min_bin_width,
93
+ min_bin_height=min_bin_height,
94
+ min_derivative=min_derivative
95
+ )
96
+
97
+ return outputs, logabsdet
98
+
99
+ def rational_quadratic_spline(inputs,
100
+ unnormalized_widths,
101
+ unnormalized_heights,
102
+ unnormalized_derivatives,
103
+ inverse=False,
104
+ left=0., right=1., bottom=0., top=1.,
105
+ min_bin_width=DEFAULT_MIN_BIN_WIDTH,
106
+ min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
107
+ min_derivative=DEFAULT_MIN_DERIVATIVE):
108
+ if torch.min(inputs) < left or torch.max(inputs) > right:
109
+ raise ValueError('Input to a transform is not within its domain')
110
+
111
+ num_bins = unnormalized_widths.shape[-1]
112
+
113
+ if min_bin_width * num_bins > 1.0:
114
+ raise ValueError('Minimal bin width too large for the number of bins')
115
+ if min_bin_height * num_bins > 1.0:
116
+ raise ValueError('Minimal bin height too large for the number of bins')
117
+
118
+ widths = F.softmax(unnormalized_widths, dim=-1)
119
+ widths = min_bin_width + (1 - min_bin_width * num_bins) * widths
120
+ cumwidths = torch.cumsum(widths, dim=-1)
121
+ cumwidths = F.pad(cumwidths, pad=(1, 0), mode='constant', value=0.0)
122
+ cumwidths = (right - left) * cumwidths + left
123
+ cumwidths[..., 0] = left
124
+ cumwidths[..., -1] = right
125
+ widths = cumwidths[..., 1:] - cumwidths[..., :-1]
126
+
127
+ derivatives = min_derivative + F.softplus(unnormalized_derivatives)
128
+
129
+ heights = F.softmax(unnormalized_heights, dim=-1)
130
+ heights = min_bin_height + (1 - min_bin_height * num_bins) * heights
131
+ cumheights = torch.cumsum(heights, dim=-1)
132
+ cumheights = F.pad(cumheights, pad=(1, 0), mode='constant', value=0.0)
133
+ cumheights = (top - bottom) * cumheights + bottom
134
+ cumheights[..., 0] = bottom
135
+ cumheights[..., -1] = top
136
+ heights = cumheights[..., 1:] - cumheights[..., :-1]
137
+
138
+ if inverse:
139
+ bin_idx = searchsorted(cumheights, inputs)[..., None]
140
+ else:
141
+ bin_idx = searchsorted(cumwidths, inputs)[..., None]
142
+
143
+ input_cumwidths = cumwidths.gather(-1, bin_idx)[..., 0]
144
+ input_bin_widths = widths.gather(-1, bin_idx)[..., 0]
145
+
146
+ input_cumheights = cumheights.gather(-1, bin_idx)[..., 0]
147
+ delta = heights / widths
148
+ input_delta = delta.gather(-1, bin_idx)[..., 0]
149
+
150
+ input_derivatives = derivatives.gather(-1, bin_idx)[..., 0]
151
+ input_derivatives_plus_one = derivatives[..., 1:].gather(-1, bin_idx)[..., 0]
152
+
153
+ input_heights = heights.gather(-1, bin_idx)[..., 0]
154
+
155
+ if inverse:
156
+ a = (((inputs - input_cumheights) * (input_derivatives
157
+ + input_derivatives_plus_one
158
+ - 2 * input_delta)
159
+ + input_heights * (input_delta - input_derivatives)))
160
+ b = (input_heights * input_derivatives
161
+ - (inputs - input_cumheights) * (input_derivatives
162
+ + input_derivatives_plus_one
163
+ - 2 * input_delta))
164
+ c = - input_delta * (inputs - input_cumheights)
165
+
166
+ discriminant = b.pow(2) - 4 * a * c
167
+ assert (discriminant >= 0).all()
168
+
169
+ root = (2 * c) / (-b - torch.sqrt(discriminant))
170
+ outputs = root * input_bin_widths + input_cumwidths
171
+
172
+ theta_one_minus_theta = root * (1 - root)
173
+ denominator = input_delta + ((input_derivatives + input_derivatives_plus_one - 2 * input_delta)
174
+ * theta_one_minus_theta)
175
+ derivative_numerator = input_delta.pow(2) * (input_derivatives_plus_one * root.pow(2)
176
+ + 2 * input_delta * theta_one_minus_theta
177
+ + input_derivatives * (1 - root).pow(2))
178
+ logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator)
179
+
180
+ return outputs, -logabsdet
181
+ else:
182
+ theta = (inputs - input_cumwidths) / input_bin_widths
183
+ theta_one_minus_theta = theta * (1 - theta)
184
+
185
+ numerator = input_heights * (input_delta * theta.pow(2)
186
+ + input_derivatives * theta_one_minus_theta)
187
+ denominator = input_delta + ((input_derivatives + input_derivatives_plus_one - 2 * input_delta)
188
+ * theta_one_minus_theta)
189
+ outputs = input_cumheights + numerator / denominator
190
+
191
+ derivative_numerator = input_delta.pow(2) * (input_derivatives_plus_one * theta.pow(2)
192
+ + 2 * input_delta * theta_one_minus_theta
193
+ + input_derivatives * (1 - theta).pow(2))
194
+ logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator)
195
+
196
+ return outputs, logabsdet
ONNXVITS_utils.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+ import random
4
+ import onnxruntime as ort
5
+ def set_random_seed(seed=0):
6
+ ort.set_seed(seed)
7
+ torch.manual_seed(seed)
8
+ torch.cuda.manual_seed(seed)
9
+ torch.backends.cudnn.deterministic = True
10
+ random.seed(seed)
11
+ np.random.seed(seed)
12
+
13
+ def runonnx(model_path, **kwargs):
14
+ ort_session = ort.InferenceSession(model_path)
15
+ outputs = ort_session.run(
16
+ None,
17
+ kwargs
18
+ )
19
+ return outputs
ONNX_net/G_jp/dec.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:559b9b8db0784cffd24e4bb3de2ec44799beb367cbf2bfa8e2868a7744463dcb
3
+ size 58201240
ONNX_net/G_jp/dp.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c4a7393ca121d3d2a21626841d9b66e49a45e6a287c88c4f707c041a58cf20bc
3
+ size 7781725
ONNX_net/G_jp/enc_p.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ad8b13ac90e35576ec57f97d879acf543f4d1c37785b8182c1ef48a87cda7106
3
+ size 28764539
ONNX_net/G_jp/flow.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:13ea432975f560f8c34fcf08fb7e6bee3278ea3e2fe97319b2c34aeb21ae657c
3
+ size 35774909
ONNX_net/G_trilingual/dec.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7b51d61f0c621f0e6531f59c0322c692aef9cc0f0cbb633f890f820027cfdbec
3
+ size 58201240
ONNX_net/G_trilingual/dp.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8b699d166d7c95648763fc322ee7ba7aadd7289f9c038dec81d14d98c0de3d5d
3
+ size 7781725
ONNX_net/G_trilingual/enc_p.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a5a4c00c85c82f916d24fe22a46fb70f5d6da9b4e122692b4561c027a514988b
3
+ size 28786043
ONNX_net/G_trilingual/flow.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7a5e74edc4d412e1857bb3a33b819d7ac4b3f6119484a775c478989b79351097
3
+ size 35774909
README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Multilingual Anime TTS
3
+ emoji: 🎙🐴
4
+ colorFrom: green
5
+ colorTo: gray
6
+ sdk: gradio
7
+ sdk_version: 3.7
8
+ app_file: app.py
9
+ pinned: false
10
+ duplicated_from: Plachta/VITS-Umamusume-voice-synthesizer
11
+ ---
12
+
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ import os
4
+ import re
5
+ import tempfile
6
+ import logging
7
+
8
+ logging.getLogger('numba').setLevel(logging.WARNING)
9
+ import librosa
10
+ import numpy as np
11
+ import torch
12
+ from torch import no_grad, LongTensor
13
+ import commons
14
+ import utils
15
+ import gradio as gr
16
+ import gradio.utils as gr_utils
17
+ import gradio.processing_utils as gr_processing_utils
18
+ import ONNXVITS_infer
19
+ import models
20
+ from text import text_to_sequence, _clean_text
21
+ from text.symbols import symbols
22
+ from mel_processing import spectrogram_torch
23
+ import psutil
24
+ from datetime import datetime
25
+
26
+ language_marks = {
27
+ "Japanese": "",
28
+ "日本語": "[JA]",
29
+ "简体中文": "[ZH]",
30
+ "English": "[EN]",
31
+ "Mix": "",
32
+ }
33
+
34
+ limitation = os.getenv("SYSTEM") == "spaces" # limit text and audio length in huggingface spaces
35
+
36
+
37
+ def create_tts_fn(model, hps, speaker_ids):
38
+ def tts_fn(text, speaker, language, speed, is_symbol):
39
+ if limitation:
40
+ text_len = len(re.sub("\[([A-Z]{2})\]", "", text))
41
+ max_len = 150
42
+ if is_symbol:
43
+ max_len *= 3
44
+ if text_len > max_len:
45
+ return "Error: Text is too long", None
46
+ if language is not None:
47
+ text = language_marks[language] + text + language_marks[language]
48
+ speaker_id = speaker_ids[speaker]
49
+ stn_tst = get_text(text, hps, is_symbol)
50
+ with no_grad():
51
+ x_tst = stn_tst.unsqueeze(0)
52
+ x_tst_lengths = LongTensor([stn_tst.size(0)])
53
+ sid = LongTensor([speaker_id])
54
+ audio = model.infer(x_tst, x_tst_lengths, sid=sid, noise_scale=.667, noise_scale_w=0.8,
55
+ length_scale=1.0 / speed)[0][0, 0].data.cpu().float().numpy()
56
+ del stn_tst, x_tst, x_tst_lengths, sid
57
+ return "Success", (hps.data.sampling_rate, audio)
58
+
59
+ return tts_fn
60
+
61
+
62
+ def create_vc_fn(model, hps, speaker_ids):
63
+ def vc_fn(original_speaker, target_speaker, input_audio):
64
+ if input_audio is None:
65
+ return "You need to upload an audio", None
66
+ sampling_rate, audio = input_audio
67
+ duration = audio.shape[0] / sampling_rate
68
+ if limitation and duration > 30:
69
+ return "Error: Audio is too long", None
70
+ original_speaker_id = speaker_ids[original_speaker]
71
+ target_speaker_id = speaker_ids[target_speaker]
72
+
73
+ audio = (audio / np.iinfo(audio.dtype).max).astype(np.float32)
74
+ if len(audio.shape) > 1:
75
+ audio = librosa.to_mono(audio.transpose(1, 0))
76
+ if sampling_rate != hps.data.sampling_rate:
77
+ audio = librosa.resample(audio, orig_sr=sampling_rate, target_sr=hps.data.sampling_rate)
78
+ with no_grad():
79
+ y = torch.FloatTensor(audio)
80
+ y = y.unsqueeze(0)
81
+ spec = spectrogram_torch(y, hps.data.filter_length,
82
+ hps.data.sampling_rate, hps.data.hop_length, hps.data.win_length,
83
+ center=False)
84
+ spec_lengths = LongTensor([spec.size(-1)])
85
+ sid_src = LongTensor([original_speaker_id])
86
+ sid_tgt = LongTensor([target_speaker_id])
87
+ audio = model.voice_conversion(spec, spec_lengths, sid_src=sid_src, sid_tgt=sid_tgt)[0][
88
+ 0, 0].data.cpu().float().numpy()
89
+ del y, spec, spec_lengths, sid_src, sid_tgt
90
+ return "Success", (hps.data.sampling_rate, audio)
91
+
92
+ return vc_fn
93
+
94
+
95
+ def get_text(text, hps, is_symbol):
96
+ text_norm = text_to_sequence(text, hps.symbols, [] if is_symbol else hps.data.text_cleaners)
97
+ if hps.data.add_blank:
98
+ text_norm = commons.intersperse(text_norm, 0)
99
+ text_norm = LongTensor(text_norm)
100
+ return text_norm
101
+
102
+
103
+ def create_to_symbol_fn(hps):
104
+ def to_symbol_fn(is_symbol_input, input_text, temp_text):
105
+ return (_clean_text(input_text, hps.data.text_cleaners), input_text) if is_symbol_input \
106
+ else (temp_text, temp_text)
107
+
108
+ return to_symbol_fn
109
+
110
+
111
+ models_tts = []
112
+ models_vc = []
113
+ models_info = [
114
+ {
115
+ "title": "Trilingual",
116
+ "languages": ['日本語', '简体中文', 'English', 'Mix'],
117
+ "description": """
118
+ This model is trained on a mix up of Umamusume, Genshin Impact, Sanoba Witch & VCTK voice data to learn multilanguage.
119
+ All characters can speak English, Chinese & Japanese.\n\n
120
+ To mix multiple languages in a single sentence, wrap the corresponding part with language tokens
121
+ ([JA] for Japanese, [ZH] for Chinese, [EN] for English), as shown in the examples.\n\n
122
+ 这个模型在赛马娘,原神,魔女的夜宴以及VCTK数据集上混合训练以学习多种语言。
123
+ 所有角色均可说中日英三语。\n\n
124
+ 若需要在同一个句子中混合多种语言,使用相应的语言标记包裹句子。
125
+ (日语用[JA], 中文用[ZH], 英文用[EN]),参考Examples中的示例。
126
+ """,
127
+ "model_path": "./pretrained_models/G_trilingual.pth",
128
+ "config_path": "./configs/uma_trilingual.json",
129
+ "examples": [['你好,训练员先生,很高兴见到你。', '草上飞 Grass Wonder (Umamusume Pretty Derby)', '简体中文', 1, False],
130
+ ['To be honest, I have no idea what to say as examples.', '派蒙 Paimon (Genshin Impact)', 'English',
131
+ 1, False],
132
+ ['授業中に出しだら,学校生活終わるですわ。', '綾地 寧々 Ayachi Nene (Sanoba Witch)', '日本語', 1, False],
133
+ ['[JA]こんにちわ。[JA][ZH]你好![ZH][EN]Hello![EN]', '綾地 寧々 Ayachi Nene (Sanoba Witch)', 'Mix', 1, False]],
134
+ "onnx_dir": "./ONNX_net/G_trilingual/"
135
+ },
136
+ {
137
+ "title": "Japanese",
138
+ "languages": ["Japanese"],
139
+ "description": """
140
+ This model contains 87 characters from Umamusume: Pretty Derby, Japanese only.\n\n
141
+ 这个模型包含赛马娘的所有87名角色,只能合成日语。
142
+ """,
143
+ "model_path": "./pretrained_models/G_jp.pth",
144
+ "config_path": "./configs/uma87.json",
145
+ "examples": [['お疲れ様です,トレーナーさん。', '无声铃鹿 Silence Suzuka (Umamusume Pretty Derby)', 'Japanese', 1, False],
146
+ ['張り切っていこう!', '北部玄驹 Kitasan Black (Umamusume Pretty Derby)', 'Japanese', 1, False],
147
+ ['何でこんなに慣れでんのよ,私のほが先に好きだっだのに。', '草上飞 Grass Wonder (Umamusume Pretty Derby)', 'Japanese', 1, False],
148
+ ['授業中に出しだら,学校生活終わるですわ。', '目白麦昆 Mejiro Mcqueen (Umamusume Pretty Derby)', 'Japanese', 1, False],
149
+ ['お帰りなさい,お兄様!', '米浴 Rice Shower (Umamusume Pretty Derby)', 'Japanese', 1, False],
150
+ ['私の処女をもらっでください!', '米浴 Rice Shower (Umamusume Pretty Derby)', 'Japanese', 1, False]],
151
+ "onnx_dir": "./ONNX_net/G_jp/"
152
+ },
153
+ ]
154
+
155
+ if __name__ == "__main__":
156
+ parser = argparse.ArgumentParser()
157
+ parser.add_argument("--share", action="store_true", default=False, help="share gradio app")
158
+ args = parser.parse_args()
159
+ for info in models_info:
160
+ name = info['title']
161
+ lang = info['languages']
162
+ examples = info['examples']
163
+ config_path = info['config_path']
164
+ model_path = info['model_path']
165
+ description = info['description']
166
+ onnx_dir = info["onnx_dir"]
167
+ hps = utils.get_hparams_from_file(config_path)
168
+ model = ONNXVITS_infer.SynthesizerTrn(
169
+ len(hps.symbols),
170
+ hps.data.filter_length // 2 + 1,
171
+ hps.train.segment_size // hps.data.hop_length,
172
+ n_speakers=hps.data.n_speakers,
173
+ ONNX_dir=onnx_dir,
174
+ **hps.model)
175
+ utils.load_checkpoint(model_path, model, None)
176
+ model.eval()
177
+ speaker_ids = hps.speakers
178
+ speakers = list(hps.speakers.keys())
179
+ models_tts.append((name, description, speakers, lang, examples,
180
+ hps.symbols, create_tts_fn(model, hps, speaker_ids),
181
+ create_to_symbol_fn(hps)))
182
+ models_vc.append((name, description, speakers, create_vc_fn(model, hps, speaker_ids)))
183
+ app = gr.Blocks()
184
+ with app:
185
+ gr.Markdown("# English & Chinese & Japanese Anime TTS\n\n"
186
+ "![visitor badge](https://visitor-badge.glitch.me/badge?page_id=Plachta.VITS-Umamusume-voice-synthesizer)\n\n"
187
+ "Including Japanese TTS & Trilingual TTS, speakers are all anime characters. \n\n包含一个纯日语TTS和一个中日英三语TTS模型,主要为二次元角色。\n\n"
188
+ "If you have any suggestions or bug reports, feel free to open discussion in [Community](https://huggingface.co/spaces/Plachta/VITS-Umamusume-voice-synthesizer/discussions).\n\n"
189
+ "若有bug反馈或建议,请在[Community](https://huggingface.co/spaces/Plachta/VITS-Umamusume-voice-synthesizer/discussions)下开启一个新的Discussion。 \n\n"
190
+ )
191
+ with gr.Tabs():
192
+ with gr.TabItem("TTS"):
193
+ with gr.Tabs():
194
+ for i, (name, description, speakers, lang, example, symbols, tts_fn, to_symbol_fn) in enumerate(
195
+ models_tts):
196
+ with gr.TabItem(name):
197
+ gr.Markdown(description)
198
+ with gr.Row():
199
+ with gr.Column():
200
+ textbox = gr.TextArea(label="Text",
201
+ placeholder="Type your sentence here (Maximum 150 words)",
202
+ value="こんにちわ。", elem_id=f"tts-input")
203
+ with gr.Accordion(label="Phoneme Input", open=False):
204
+ temp_text_var = gr.Variable()
205
+ symbol_input = gr.Checkbox(value=False, label="Symbol input")
206
+ symbol_list = gr.Dataset(label="Symbol list", components=[textbox],
207
+ samples=[[x] for x in symbols],
208
+ elem_id=f"symbol-list")
209
+ symbol_list_json = gr.Json(value=symbols, visible=False)
210
+ symbol_input.change(to_symbol_fn,
211
+ [symbol_input, textbox, temp_text_var],
212
+ [textbox, temp_text_var])
213
+ symbol_list.click(None, [symbol_list, symbol_list_json], textbox,
214
+ _js=f"""
215
+ (i, symbols, text) => {{
216
+ let root = document.querySelector("body > gradio-app");
217
+ if (root.shadowRoot != null)
218
+ root = root.shadowRoot;
219
+ let text_input = root.querySelector("#tts-input").querySelector("textarea");
220
+ let startPos = text_input.selectionStart;
221
+ let endPos = text_input.selectionEnd;
222
+ let oldTxt = text_input.value;
223
+ let result = oldTxt.substring(0, startPos) + symbols[i] + oldTxt.substring(endPos);
224
+ text_input.value = result;
225
+ let x = window.scrollX, y = window.scrollY;
226
+ text_input.focus();
227
+ text_input.selectionStart = startPos + symbols[i].length;
228
+ text_input.selectionEnd = startPos + symbols[i].length;
229
+ text_input.blur();
230
+ window.scrollTo(x, y);
231
+
232
+ text = text_input.value;
233
+
234
+ return text;
235
+ }}""")
236
+ # select character
237
+ char_dropdown = gr.Dropdown(choices=speakers, value=speakers[0], label='character')
238
+ language_dropdown = gr.Dropdown(choices=lang, value=lang[0], label='language')
239
+ duration_slider = gr.Slider(minimum=0.1, maximum=5, value=1, step=0.1,
240
+ label='速度 Speed')
241
+ with gr.Column():
242
+ text_output = gr.Textbox(label="Message")
243
+ audio_output = gr.Audio(label="Output Audio", elem_id="tts-audio")
244
+ btn = gr.Button("Generate!")
245
+ btn.click(tts_fn,
246
+ inputs=[textbox, char_dropdown, language_dropdown, duration_slider,
247
+ symbol_input],
248
+ outputs=[text_output, audio_output])
249
+ gr.Examples(
250
+ examples=example,
251
+ inputs=[textbox, char_dropdown, language_dropdown,
252
+ duration_slider, symbol_input],
253
+ outputs=[text_output, audio_output],
254
+ fn=tts_fn
255
+ )
256
+ app.queue(concurrency_count=3).launch(show_api=False, share=args.share)
attentions.py ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ from torch import nn
4
+ from torch.nn import functional as F
5
+
6
+ import commons
7
+ from modules import LayerNorm
8
+
9
+
10
+ class Encoder(nn.Module):
11
+ def __init__(self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0., window_size=4, **kwargs):
12
+ super().__init__()
13
+ self.hidden_channels = hidden_channels
14
+ self.filter_channels = filter_channels
15
+ self.n_heads = n_heads
16
+ self.n_layers = n_layers
17
+ self.kernel_size = kernel_size
18
+ self.p_dropout = p_dropout
19
+ self.window_size = window_size
20
+
21
+ self.drop = nn.Dropout(p_dropout)
22
+ self.attn_layers = nn.ModuleList()
23
+ self.norm_layers_1 = nn.ModuleList()
24
+ self.ffn_layers = nn.ModuleList()
25
+ self.norm_layers_2 = nn.ModuleList()
26
+ for i in range(self.n_layers):
27
+ self.attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout, window_size=window_size))
28
+ self.norm_layers_1.append(LayerNorm(hidden_channels))
29
+ self.ffn_layers.append(FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout))
30
+ self.norm_layers_2.append(LayerNorm(hidden_channels))
31
+
32
+ def forward(self, x, x_mask):
33
+ attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
34
+ x = x * x_mask
35
+ for i in range(self.n_layers):
36
+ y = self.attn_layers[i](x, x, attn_mask)
37
+ y = self.drop(y)
38
+ x = self.norm_layers_1[i](x + y)
39
+
40
+ y = self.ffn_layers[i](x, x_mask)
41
+ y = self.drop(y)
42
+ x = self.norm_layers_2[i](x + y)
43
+ x = x * x_mask
44
+ return x
45
+
46
+
47
+ class Decoder(nn.Module):
48
+ def __init__(self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0., proximal_bias=False, proximal_init=True, **kwargs):
49
+ super().__init__()
50
+ self.hidden_channels = hidden_channels
51
+ self.filter_channels = filter_channels
52
+ self.n_heads = n_heads
53
+ self.n_layers = n_layers
54
+ self.kernel_size = kernel_size
55
+ self.p_dropout = p_dropout
56
+ self.proximal_bias = proximal_bias
57
+ self.proximal_init = proximal_init
58
+
59
+ self.drop = nn.Dropout(p_dropout)
60
+ self.self_attn_layers = nn.ModuleList()
61
+ self.norm_layers_0 = nn.ModuleList()
62
+ self.encdec_attn_layers = nn.ModuleList()
63
+ self.norm_layers_1 = nn.ModuleList()
64
+ self.ffn_layers = nn.ModuleList()
65
+ self.norm_layers_2 = nn.ModuleList()
66
+ for i in range(self.n_layers):
67
+ self.self_attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout, proximal_bias=proximal_bias, proximal_init=proximal_init))
68
+ self.norm_layers_0.append(LayerNorm(hidden_channels))
69
+ self.encdec_attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout))
70
+ self.norm_layers_1.append(LayerNorm(hidden_channels))
71
+ self.ffn_layers.append(FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout, causal=True))
72
+ self.norm_layers_2.append(LayerNorm(hidden_channels))
73
+
74
+ def forward(self, x, x_mask, h, h_mask):
75
+ """
76
+ x: decoder input
77
+ h: encoder output
78
+ """
79
+ self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(device=x.device, dtype=x.dtype)
80
+ encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
81
+ x = x * x_mask
82
+ for i in range(self.n_layers):
83
+ y = self.self_attn_layers[i](x, x, self_attn_mask)
84
+ y = self.drop(y)
85
+ x = self.norm_layers_0[i](x + y)
86
+
87
+ y = self.encdec_attn_layers[i](x, h, encdec_attn_mask)
88
+ y = self.drop(y)
89
+ x = self.norm_layers_1[i](x + y)
90
+
91
+ y = self.ffn_layers[i](x, x_mask)
92
+ y = self.drop(y)
93
+ x = self.norm_layers_2[i](x + y)
94
+ x = x * x_mask
95
+ return x
96
+
97
+
98
+ class MultiHeadAttention(nn.Module):
99
+ def __init__(self, channels, out_channels, n_heads, p_dropout=0., window_size=None, heads_share=True, block_length=None, proximal_bias=False, proximal_init=False):
100
+ super().__init__()
101
+ assert channels % n_heads == 0
102
+
103
+ self.channels = channels
104
+ self.out_channels = out_channels
105
+ self.n_heads = n_heads
106
+ self.p_dropout = p_dropout
107
+ self.window_size = window_size
108
+ self.heads_share = heads_share
109
+ self.block_length = block_length
110
+ self.proximal_bias = proximal_bias
111
+ self.proximal_init = proximal_init
112
+ self.attn = None
113
+
114
+ self.k_channels = channels // n_heads
115
+ self.conv_q = nn.Conv1d(channels, channels, 1)
116
+ self.conv_k = nn.Conv1d(channels, channels, 1)
117
+ self.conv_v = nn.Conv1d(channels, channels, 1)
118
+ self.conv_o = nn.Conv1d(channels, out_channels, 1)
119
+ self.drop = nn.Dropout(p_dropout)
120
+
121
+ if window_size is not None:
122
+ n_heads_rel = 1 if heads_share else n_heads
123
+ rel_stddev = self.k_channels**-0.5
124
+ self.emb_rel_k = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev)
125
+ self.emb_rel_v = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev)
126
+
127
+ nn.init.xavier_uniform_(self.conv_q.weight)
128
+ nn.init.xavier_uniform_(self.conv_k.weight)
129
+ nn.init.xavier_uniform_(self.conv_v.weight)
130
+ if proximal_init:
131
+ with torch.no_grad():
132
+ self.conv_k.weight.copy_(self.conv_q.weight)
133
+ self.conv_k.bias.copy_(self.conv_q.bias)
134
+
135
+ def forward(self, x, c, attn_mask=None):
136
+ q = self.conv_q(x)
137
+ k = self.conv_k(c)
138
+ v = self.conv_v(c)
139
+
140
+ x, self.attn = self.attention(q, k, v, mask=attn_mask)
141
+
142
+ x = self.conv_o(x)
143
+ return x
144
+
145
+ def attention(self, query, key, value, mask=None):
146
+ # reshape [b, d, t] -> [b, n_h, t, d_k]
147
+ b, d, t_s, t_t = (*key.size(), query.size(2))
148
+ query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3)
149
+ key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
150
+ value = value.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
151
+
152
+ scores = torch.matmul(query / math.sqrt(self.k_channels), key.transpose(-2, -1))
153
+ if self.window_size is not None:
154
+ assert t_s == t_t, "Relative attention is only available for self-attention."
155
+ key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s)
156
+ rel_logits = self._matmul_with_relative_keys(query /math.sqrt(self.k_channels), key_relative_embeddings)
157
+ scores_local = self._relative_position_to_absolute_position(rel_logits)
158
+ scores = scores + scores_local
159
+ if self.proximal_bias:
160
+ assert t_s == t_t, "Proximal bias is only available for self-attention."
161
+ scores = scores + self._attention_bias_proximal(t_s).to(device=scores.device, dtype=scores.dtype)
162
+ if mask is not None:
163
+ scores = scores.masked_fill(mask == 0, -1e4)
164
+ if self.block_length is not None:
165
+ assert t_s == t_t, "Local attention is only available for self-attention."
166
+ block_mask = torch.ones_like(scores).triu(-self.block_length).tril(self.block_length)
167
+ scores = scores.masked_fill(block_mask == 0, -1e4)
168
+ p_attn = F.softmax(scores, dim=-1) # [b, n_h, t_t, t_s]
169
+ p_attn = self.drop(p_attn)
170
+ output = torch.matmul(p_attn, value)
171
+ if self.window_size is not None:
172
+ relative_weights = self._absolute_position_to_relative_position(p_attn)
173
+ value_relative_embeddings = self._get_relative_embeddings(self.emb_rel_v, t_s)
174
+ output = output + self._matmul_with_relative_values(relative_weights, value_relative_embeddings)
175
+ output = output.transpose(2, 3).contiguous().view(b, d, t_t) # [b, n_h, t_t, d_k] -> [b, d, t_t]
176
+ return output, p_attn
177
+
178
+ def _matmul_with_relative_values(self, x, y):
179
+ """
180
+ x: [b, h, l, m]
181
+ y: [h or 1, m, d]
182
+ ret: [b, h, l, d]
183
+ """
184
+ ret = torch.matmul(x, y.unsqueeze(0))
185
+ return ret
186
+
187
+ def _matmul_with_relative_keys(self, x, y):
188
+ """
189
+ x: [b, h, l, d]
190
+ y: [h or 1, m, d]
191
+ ret: [b, h, l, m]
192
+ """
193
+ ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1))
194
+ return ret
195
+
196
+ def _get_relative_embeddings(self, relative_embeddings, length):
197
+ max_relative_position = 2 * self.window_size + 1
198
+ # Pad first before slice to avoid using cond ops.
199
+ pad_length = max(length - (self.window_size + 1), 0)
200
+ slice_start_position = max((self.window_size + 1) - length, 0)
201
+ slice_end_position = slice_start_position + 2 * length - 1
202
+ if pad_length > 0:
203
+ padded_relative_embeddings = F.pad(
204
+ relative_embeddings,
205
+ commons.convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]]))
206
+ else:
207
+ padded_relative_embeddings = relative_embeddings
208
+ used_relative_embeddings = padded_relative_embeddings[:,slice_start_position:slice_end_position]
209
+ return used_relative_embeddings
210
+
211
+ def _relative_position_to_absolute_position(self, x):
212
+ """
213
+ x: [b, h, l, 2*l-1]
214
+ ret: [b, h, l, l]
215
+ """
216
+ batch, heads, length, _ = x.size()
217
+ # Concat columns of pad to shift from relative to absolute indexing.
218
+ x = F.pad(x, commons.convert_pad_shape([[0,0],[0,0],[0,0],[0,1]]))
219
+
220
+ # Concat extra elements so to add up to shape (len+1, 2*len-1).
221
+ x_flat = x.view([batch, heads, length * 2 * length])
222
+ x_flat = F.pad(x_flat, commons.convert_pad_shape([[0,0],[0,0],[0,length-1]]))
223
+
224
+ # Reshape and slice out the padded elements.
225
+ x_final = x_flat.view([batch, heads, length+1, 2*length-1])[:, :, :length, length-1:]
226
+ return x_final
227
+
228
+ def _absolute_position_to_relative_position(self, x):
229
+ """
230
+ x: [b, h, l, l]
231
+ ret: [b, h, l, 2*l-1]
232
+ """
233
+ batch, heads, length, _ = x.size()
234
+ # padd along column
235
+ x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length-1]]))
236
+ x_flat = x.view([batch, heads, length**2 + length*(length -1)])
237
+ # add 0's in the beginning that will skew the elements after reshape
238
+ x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [length, 0]]))
239
+ x_final = x_flat.view([batch, heads, length, 2*length])[:,:,:,1:]
240
+ return x_final
241
+
242
+ def _attention_bias_proximal(self, length):
243
+ """Bias for self-attention to encourage attention to close positions.
244
+ Args:
245
+ length: an integer scalar.
246
+ Returns:
247
+ a Tensor with shape [1, 1, length, length]
248
+ """
249
+ r = torch.arange(length, dtype=torch.float32)
250
+ diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1)
251
+ return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)
252
+
253
+
254
+ class FFN(nn.Module):
255
+ def __init__(self, in_channels, out_channels, filter_channels, kernel_size, p_dropout=0., activation=None, causal=False):
256
+ super().__init__()
257
+ self.in_channels = in_channels
258
+ self.out_channels = out_channels
259
+ self.filter_channels = filter_channels
260
+ self.kernel_size = kernel_size
261
+ self.p_dropout = p_dropout
262
+ self.activation = activation
263
+ self.causal = causal
264
+
265
+ if causal:
266
+ self.padding = self._causal_padding
267
+ else:
268
+ self.padding = self._same_padding
269
+
270
+ self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size)
271
+ self.conv_2 = nn.Conv1d(filter_channels, out_channels, kernel_size)
272
+ self.drop = nn.Dropout(p_dropout)
273
+
274
+ def forward(self, x, x_mask):
275
+ x = self.conv_1(self.padding(x * x_mask))
276
+ if self.activation == "gelu":
277
+ x = x * torch.sigmoid(1.702 * x)
278
+ else:
279
+ x = torch.relu(x)
280
+ x = self.drop(x)
281
+ x = self.conv_2(self.padding(x * x_mask))
282
+ return x * x_mask
283
+
284
+ def _causal_padding(self, x):
285
+ if self.kernel_size == 1:
286
+ return x
287
+ pad_l = self.kernel_size - 1
288
+ pad_r = 0
289
+ padding = [[0, 0], [0, 0], [pad_l, pad_r]]
290
+ x = F.pad(x, commons.convert_pad_shape(padding))
291
+ return x
292
+
293
+ def _same_padding(self, x):
294
+ if self.kernel_size == 1:
295
+ return x
296
+ pad_l = (self.kernel_size - 1) // 2
297
+ pad_r = self.kernel_size // 2
298
+ padding = [[0, 0], [0, 0], [pad_l, pad_r]]
299
+ x = F.pad(x, commons.convert_pad_shape(padding))
300
+ return x
commons.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ from torch.nn import functional as F
4
+ import torch.jit
5
+
6
+
7
+ def script_method(fn, _rcb=None):
8
+ return fn
9
+
10
+
11
+ def script(obj, optimize=True, _frames_up=0, _rcb=None):
12
+ return obj
13
+
14
+
15
+ torch.jit.script_method = script_method
16
+ torch.jit.script = script
17
+
18
+
19
+ def init_weights(m, mean=0.0, std=0.01):
20
+ classname = m.__class__.__name__
21
+ if classname.find("Conv") != -1:
22
+ m.weight.data.normal_(mean, std)
23
+
24
+
25
+ def get_padding(kernel_size, dilation=1):
26
+ return int((kernel_size*dilation - dilation)/2)
27
+
28
+
29
+ def intersperse(lst, item):
30
+ result = [item] * (len(lst) * 2 + 1)
31
+ result[1::2] = lst
32
+ return result
33
+
34
+
35
+ def slice_segments(x, ids_str, segment_size=4):
36
+ ret = torch.zeros_like(x[:, :, :segment_size])
37
+ for i in range(x.size(0)):
38
+ idx_str = ids_str[i]
39
+ idx_end = idx_str + segment_size
40
+ ret[i] = x[i, :, idx_str:idx_end]
41
+ return ret
42
+
43
+
44
+ def rand_slice_segments(x, x_lengths=None, segment_size=4):
45
+ b, d, t = x.size()
46
+ if x_lengths is None:
47
+ x_lengths = t
48
+ ids_str_max = x_lengths - segment_size + 1
49
+ ids_str = (torch.rand([b]).to(device=x.device) * ids_str_max).to(dtype=torch.long)
50
+ ret = slice_segments(x, ids_str, segment_size)
51
+ return ret, ids_str
52
+
53
+
54
+ def subsequent_mask(length):
55
+ mask = torch.tril(torch.ones(length, length)).unsqueeze(0).unsqueeze(0)
56
+ return mask
57
+
58
+
59
+ @torch.jit.script
60
+ def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
61
+ n_channels_int = n_channels[0]
62
+ in_act = input_a + input_b
63
+ t_act = torch.tanh(in_act[:, :n_channels_int, :])
64
+ s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
65
+ acts = t_act * s_act
66
+ return acts
67
+
68
+
69
+ def convert_pad_shape(pad_shape):
70
+ l = pad_shape[::-1]
71
+ pad_shape = [item for sublist in l for item in sublist]
72
+ return pad_shape
73
+
74
+
75
+ def sequence_mask(length, max_length=None):
76
+ if max_length is None:
77
+ max_length = length.max()
78
+ x = torch.arange(max_length, dtype=length.dtype, device=length.device)
79
+ return x.unsqueeze(0) < length.unsqueeze(1)
80
+
81
+
82
+ def generate_path(duration, mask):
83
+ """
84
+ duration: [b, 1, t_x]
85
+ mask: [b, 1, t_y, t_x]
86
+ """
87
+ device = duration.device
88
+
89
+ b, _, t_y, t_x = mask.shape
90
+ cum_duration = torch.cumsum(duration, -1)
91
+
92
+ cum_duration_flat = cum_duration.view(b * t_x)
93
+ path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype)
94
+ path = path.view(b, t_x, t_y)
95
+ path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1]
96
+ path = path.unsqueeze(1).transpose(2,3) * mask
97
+ return path
configs/uma87.json ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "train": {
3
+ "log_interval": 200,
4
+ "eval_interval": 1000,
5
+ "seed": 1234,
6
+ "epochs": 10000,
7
+ "learning_rate": 2e-4,
8
+ "betas": [0.8, 0.99],
9
+ "eps": 1e-9,
10
+ "batch_size": 1,
11
+ "fp16_run": true,
12
+ "lr_decay": 0.999875,
13
+ "segment_size": 8192,
14
+ "init_lr_ratio": 1,
15
+ "warmup_epochs": 0,
16
+ "c_mel": 45,
17
+ "c_kl": 1.0
18
+ },
19
+ "data": {
20
+ "training_files":"E:/uma_voice/output_train.txt.cleaned",
21
+ "validation_files":"E:/uma_voice/output_val.txt.cleaned",
22
+ "text_cleaners":["japanese_cleaners"],
23
+ "max_wav_value": 32768.0,
24
+ "sampling_rate": 22050,
25
+ "filter_length": 1024,
26
+ "hop_length": 256,
27
+ "win_length": 1024,
28
+ "n_mel_channels": 80,
29
+ "mel_fmin": 0.0,
30
+ "mel_fmax": null,
31
+ "add_blank": true,
32
+ "n_speakers": 87,
33
+ "cleaned_text": true
34
+ },
35
+ "model": {
36
+ "inter_channels": 192,
37
+ "hidden_channels": 192,
38
+ "filter_channels": 768,
39
+ "n_heads": 2,
40
+ "n_layers": 6,
41
+ "kernel_size": 3,
42
+ "p_dropout": 0.1,
43
+ "resblock": "1",
44
+ "resblock_kernel_sizes": [3,7,11],
45
+ "resblock_dilation_sizes": [[1,3,5], [1,3,5], [1,3,5]],
46
+ "upsample_rates": [8,8,2,2],
47
+ "upsample_initial_channel": 512,
48
+ "upsample_kernel_sizes": [16,16,4,4],
49
+ "n_layers_q": 3,
50
+ "use_spectral_norm": false,
51
+ "gin_channels": 256
52
+ },
53
+ "speakers": {"特别周 Special Week (Umamusume Pretty Derby)": 0,
54
+ "无声铃鹿 Silence Suzuka (Umamusume Pretty Derby)": 1,
55
+ "东海帝王 Tokai Teio (Umamusume Pretty Derby)": 2,
56
+ "丸善斯基 Maruzensky (Umamusume Pretty Derby)": 3,
57
+ "富士奇迹 Fuji Kiseki (Umamusume Pretty Derby)": 4,
58
+ "小栗帽 Oguri Cap (Umamusume Pretty Derby)": 5,
59
+ "黄金船 Gold Ship (Umamusume Pretty Derby)": 6,
60
+ "伏特加 Vodka (Umamusume Pretty Derby)": 7,
61
+ "大和赤骥 Daiwa Scarlet (Umamusume Pretty Derby)": 8,
62
+ "大树快车 Taiki Shuttle (Umamusume Pretty Derby)": 9,
63
+ "草上飞 Grass Wonder (Umamusume Pretty Derby)": 10,
64
+ "菱亚马逊 Hishi Amazon (Umamusume Pretty Derby)": 11,
65
+ "目白麦昆 Mejiro Mcqueen (Umamusume Pretty Derby)": 12,
66
+ "神鹰 El Condor Pasa (Umamusume Pretty Derby)": 13,
67
+ "好歌剧 T.M. Opera O (Umamusume Pretty Derby)": 14,
68
+ "成田白仁 Narita Brian (Umamusume Pretty Derby)": 15,
69
+ "鲁道夫象征 Symboli Rudolf (Umamusume Pretty Derby)": 16,
70
+ "气槽 Air Groove (Umamusume Pretty Derby)": 17,
71
+ "爱丽数码 Agnes Digital (Umamusume Pretty Derby)": 18,
72
+ "青云天空 Seiun Sky (Umamusume Pretty Derby)": 19,
73
+ "玉藻十字 Tamamo Cross (Umamusume Pretty Derby)": 20,
74
+ "美妙姿势 Fine Motion (Umamusume Pretty Derby)": 21,
75
+ "琵琶晨光 Biwa Hayahide (Umamusume Pretty Derby)": 22,
76
+ "重炮 Mayano Topgun (Umamusume Pretty Derby)": 23,
77
+ "曼城茶座 Manhattan Cafe (Umamusume Pretty Derby)": 24,
78
+ "美普波旁 Mihono Bourbon (Umamusume Pretty Derby)": 25,
79
+ "目白雷恩 Mejiro Ryan (Umamusume Pretty Derby)": 26,
80
+ "雪之美人 Yukino Bijin (Umamusume Pretty Derby)": 28,
81
+ "米浴 Rice Shower (Umamusume Pretty Derby)": 29,
82
+ "艾尼斯风神 Ines Fujin (Umamusume Pretty Derby)": 30,
83
+ "爱丽速子 Agnes Tachyon (Umamusume Pretty Derby)": 31,
84
+ "爱慕织姬 Admire Vega (Umamusume Pretty Derby)": 32,
85
+ "稻荷一 Inari One (Umamusume Pretty Derby)": 33,
86
+ "胜利奖券 Winning Ticket (Umamusume Pretty Derby)": 34,
87
+ "空中神宫 Air Shakur (Umamusume Pretty Derby)": 35,
88
+ "荣进闪耀 Eishin Flash (Umamusume Pretty Derby)": 36,
89
+ "真机伶 Curren Chan (Umamusume Pretty Derby)": 37,
90
+ "川上公主 Kawakami Princess (Umamusume Pretty Derby)": 38,
91
+ "黄金城市 Gold City (Umamusume Pretty Derby)": 39,
92
+ "樱花进王 Sakura Bakushin O (Umamusume Pretty Derby)": 40,
93
+ "采珠 Seeking the Pearl (Umamusume Pretty Derby)": 41,
94
+ "新光风 Shinko Windy (Umamusume Pretty Derby)": 42,
95
+ "东商变革 Sweep Tosho (Umamusume Pretty Derby)": 43,
96
+ "超级小溪 Super Creek (Umamusume Pretty Derby)": 44,
97
+ "醒目飞鹰 Smart Falcon (Umamusume Pretty Derby)": 45,
98
+ "荒漠英雄 Zenno Rob Roy (Umamusume Pretty Derby)": 46,
99
+ "东瀛佐敦 Tosen Jordan (Umamusume Pretty Derby)": 47,
100
+ "中山庆典 Nakayama Festa (Umamusume Pretty Derby)": 48,
101
+ "成田大进 Narita Taishin (Umamusume Pretty Derby)": 49,
102
+ "西野花 Nishino Flower (Umamusume Pretty Derby)": 50,
103
+ "春乌拉拉 Haru Urara (Umamusume Pretty Derby)": 51,
104
+ "青竹回忆 Bamboo Memory (Umamusume Pretty Derby)": 52,
105
+ "待兼福来 Matikane Fukukitaru (Umamusume Pretty Derby)": 55,
106
+ "名将怒涛 Meisho Doto (Umamusume Pretty Derby)": 57,
107
+ "目白多伯 Mejiro Dober (Umamusume Pretty Derby)": 58,
108
+ "优秀素质 Nice Nature (Umamusume Pretty Derby)": 59,
109
+ "帝王光环 King Halo (Umamusume Pretty Derby)": 60,
110
+ "待兼诗歌剧 Matikane Tannhauser (Umamusume Pretty Derby)": 61,
111
+ "生野狄杜斯 Ikuno Dictus (Umamusume Pretty Derby)": 62,
112
+ "目白善信 Mejiro Palmer (Umamusume Pretty Derby)": 63,
113
+ "大拓太阳神 Daitaku Helios (Umamusume Pretty Derby)": 64,
114
+ "双涡轮 Twin Turbo (Umamusume Pretty Derby)": 65,
115
+ "里见光钻 Satono Diamond (Umamusume Pretty Derby)": 66,
116
+ "北部玄驹 Kitasan Black (Umamusume Pretty Derby)": 67,
117
+ "樱花千代王 Sakura Chiyono O (Umamusume Pretty Derby)": 68,
118
+ "天狼星象征 Sirius Symboli (Umamusume Pretty Derby)": 69,
119
+ "目白阿尔丹 Mejiro Ardan (Umamusume Pretty Derby)": 70,
120
+ "八重无敌 Yaeno Muteki (Umamusume Pretty Derby)": 71,
121
+ "鹤丸刚志 Tsurumaru Tsuyoshi (Umamusume Pretty Derby)": 72,
122
+ "目白光明 Mejiro Bright (Umamusume Pretty Derby)": 73,
123
+ "樱花桂冠 Sakura Laurel (Umamusume Pretty Derby)": 74,
124
+ "成田路 Narita Top Road (Umamusume Pretty Derby)": 75,
125
+ "也文摄辉 Yamanin Zephyr (Umamusume Pretty Derby)": 76,
126
+ "真弓快车 Aston Machan (Umamusume Pretty Derby)": 80,
127
+ "骏川手纲 Hayakawa Tazuna (Umamusume Pretty Derby)": 81,
128
+ "小林历奇 Kopano Rickey (Umamusume Pretty Derby)": 83,
129
+ "奇锐骏 Wonder Acute (Umamusume Pretty Derby)": 85,
130
+ "秋川理事长 President Akikawa (Umamusume Pretty Derby)": 86
131
+ },
132
+ "symbols": ["_", ",", ".", "!", "?", "-", "A", "E", "I", "N", "O", "Q", "U", "a", "b", "d", "e", "f", "g", "h", "i", "j", "k", "m", "n", "o", "p", "r", "s", "t", "u", "v", "w", "y", "z", "\u0283", "\u02a7", "\u2193", "\u2191", " "]
133
+ }
configs/uma_trilingual.json ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "train": {
3
+ "log_interval": 200,
4
+ "eval_interval": 1000,
5
+ "seed": 1234,
6
+ "epochs": 10000,
7
+ "learning_rate": 2e-4,
8
+ "betas": [0.8, 0.99],
9
+ "eps": 1e-9,
10
+ "batch_size": 16,
11
+ "fp16_run": true,
12
+ "lr_decay": 0.999875,
13
+ "segment_size": 8192,
14
+ "init_lr_ratio": 1,
15
+ "warmup_epochs": 0,
16
+ "c_mel": 45,
17
+ "c_kl": 1.0
18
+ },
19
+ "data": {
20
+ "training_files":"../CH_JA_EN_mix_voice/clipped_3_vits_trilingual_annotations.train.txt.cleaned",
21
+ "validation_files":"../CH_JA_EN_mix_voice/clipped_3_vits_trilingual_annotations.val.txt.cleaned",
22
+ "text_cleaners":["cjke_cleaners2"],
23
+ "max_wav_value": 32768.0,
24
+ "sampling_rate": 22050,
25
+ "filter_length": 1024,
26
+ "hop_length": 256,
27
+ "win_length": 1024,
28
+ "n_mel_channels": 80,
29
+ "mel_fmin": 0.0,
30
+ "mel_fmax": null,
31
+ "add_blank": true,
32
+ "n_speakers": 999,
33
+ "cleaned_text": true
34
+ },
35
+ "model": {
36
+ "inter_channels": 192,
37
+ "hidden_channels": 192,
38
+ "filter_channels": 768,
39
+ "n_heads": 2,
40
+ "n_layers": 6,
41
+ "kernel_size": 3,
42
+ "p_dropout": 0.1,
43
+ "resblock": "1",
44
+ "resblock_kernel_sizes": [3,7,11],
45
+ "resblock_dilation_sizes": [[1,3,5], [1,3,5], [1,3,5]],
46
+ "upsample_rates": [8,8,2,2],
47
+ "upsample_initial_channel": 512,
48
+ "upsample_kernel_sizes": [16,16,4,4],
49
+ "n_layers_q": 3,
50
+ "use_spectral_norm": false,
51
+ "gin_channels": 256
52
+ },
53
+ "symbols": ["_", ",", ".", "!", "?", "-", "~", "\u2026", "N", "Q", "a", "b", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "s", "t", "u", "v", "w", "x", "y", "z", "\u0251", "\u00e6", "\u0283", "\u0291", "\u00e7", "\u026f", "\u026a", "\u0254", "\u025b", "\u0279", "\u00f0", "\u0259", "\u026b", "\u0265", "\u0278", "\u028a", "\u027e", "\u0292", "\u03b8", "\u03b2", "\u014b", "\u0266", "\u207c", "\u02b0", "`", "^", "#", "*", "=", "\u02c8", "\u02cc", "\u2192", "\u2193", "\u2191", " "],
54
+ "speakers": {"特别周 Special Week (Umamusume Pretty Derby)": 0,
55
+ "无声铃鹿 Silence Suzuka (Umamusume Pretty Derby)": 1,
56
+ "东海帝王 Tokai Teio (Umamusume Pretty Derby)": 2,
57
+ "丸善斯基 Maruzensky (Umamusume Pretty Derby)": 3,
58
+ "富士奇迹 Fuji Kiseki (Umamusume Pretty Derby)": 4,
59
+ "小栗帽 Oguri Cap (Umamusume Pretty Derby)": 5,
60
+ "黄金船 Gold Ship (Umamusume Pretty Derby)": 6,
61
+ "伏特加 Vodka (Umamusume Pretty Derby)": 7,
62
+ "大和赤骥 Daiwa Scarlet (Umamusume Pretty Derby)": 8,
63
+ "大树快车 Taiki Shuttle (Umamusume Pretty Derby)": 9,
64
+ "草上飞 Grass Wonder (Umamusume Pretty Derby)": 10,
65
+ "菱亚马逊 Hishi Amazon (Umamusume Pretty Derby)": 11,
66
+ "目白麦昆 Mejiro Mcqueen (Umamusume Pretty Derby)": 12,
67
+ "神鹰 El Condor Pasa (Umamusume Pretty Derby)": 13,
68
+ "好歌剧 T.M. Opera O (Umamusume Pretty Derby)": 14,
69
+ "成田白仁 Narita Brian (Umamusume Pretty Derby)": 15,
70
+ "鲁道夫象征 Symboli Rudolf (Umamusume Pretty Derby)": 16,
71
+ "气槽 Air Groove (Umamusume Pretty Derby)": 17,
72
+ "爱丽数码 Agnes Digital (Umamusume Pretty Derby)": 18,
73
+ "青云天空 Seiun Sky (Umamusume Pretty Derby)": 19,
74
+ "玉藻十字 Tamamo Cross (Umamusume Pretty Derby)": 20,
75
+ "美妙姿势 Fine Motion (Umamusume Pretty Derby)": 21,
76
+ "琵琶晨光 Biwa Hayahide (Umamusume Pretty Derby)": 22,
77
+ "重炮 Mayano Topgun (Umamusume Pretty Derby)": 23,
78
+ "曼城茶座 Manhattan Cafe (Umamusume Pretty Derby)": 24,
79
+ "美普波旁 Mihono Bourbon (Umamusume Pretty Derby)": 25,
80
+ "目白雷恩 Mejiro Ryan (Umamusume Pretty Derby)": 26,
81
+ "雪之美人 Yukino Bijin (Umamusume Pretty Derby)": 28,
82
+ "米浴 Rice Shower (Umamusume Pretty Derby)": 29,
83
+ "艾尼斯风神 Ines Fujin (Umamusume Pretty Derby)": 30,
84
+ "爱丽速子 Agnes Tachyon (Umamusume Pretty Derby)": 31,
85
+ "爱慕织姬 Admire Vega (Umamusume Pretty Derby)": 32,
86
+ "稻荷一 Inari One (Umamusume Pretty Derby)": 33,
87
+ "胜利奖券 Winning Ticket (Umamusume Pretty Derby)": 34,
88
+ "空中神宫 Air Shakur (Umamusume Pretty Derby)": 35,
89
+ "荣进闪耀 Eishin Flash (Umamusume Pretty Derby)": 36,
90
+ "真机伶 Curren Chan (Umamusume Pretty Derby)": 37,
91
+ "川上公主 Kawakami Princess (Umamusume Pretty Derby)": 38,
92
+ "黄金城市 Gold City (Umamusume Pretty Derby)": 39,
93
+ "樱花进王 Sakura Bakushin O (Umamusume Pretty Derby)": 40,
94
+ "采珠 Seeking the Pearl (Umamusume Pretty Derby)": 41,
95
+ "新光风 Shinko Windy (Umamusume Pretty Derby)": 42,
96
+ "东商变革 Sweep Tosho (Umamusume Pretty Derby)": 43,
97
+ "超级小溪 Super Creek (Umamusume Pretty Derby)": 44,
98
+ "醒目飞鹰 Smart Falcon (Umamusume Pretty Derby)": 45,
99
+ "荒漠英雄 Zenno Rob Roy (Umamusume Pretty Derby)": 46,
100
+ "东瀛佐敦 Tosen Jordan (Umamusume Pretty Derby)": 47,
101
+ "中山庆典 Nakayama Festa (Umamusume Pretty Derby)": 48,
102
+ "成田大进 Narita Taishin (Umamusume Pretty Derby)": 49,
103
+ "西野花 Nishino Flower (Umamusume Pretty Derby)": 50,
104
+ "春乌拉拉 Haru Urara (Umamusume Pretty Derby)": 51,
105
+ "青竹回忆 Bamboo Memory (Umamusume Pretty Derby)": 52,
106
+ "待兼福来 Matikane Fukukitaru (Umamusume Pretty Derby)": 55,
107
+ "名将怒涛 Meisho Doto (Umamusume Pretty Derby)": 57,
108
+ "目白多伯 Mejiro Dober (Umamusume Pretty Derby)": 58,
109
+ "优秀素质 Nice Nature (Umamusume Pretty Derby)": 59,
110
+ "帝王光环 King Halo (Umamusume Pretty Derby)": 60,
111
+ "待兼诗歌剧 Matikane Tannhauser (Umamusume Pretty Derby)": 61,
112
+ "生野狄杜斯 Ikuno Dictus (Umamusume Pretty Derby)": 62,
113
+ "目白善信 Mejiro Palmer (Umamusume Pretty Derby)": 63,
114
+ "大拓太阳神 Daitaku Helios (Umamusume Pretty Derby)": 64,
115
+ "双涡轮 Twin Turbo (Umamusume Pretty Derby)": 65,
116
+ "里见光钻 Satono Diamond (Umamusume Pretty Derby)": 66,
117
+ "北部玄驹 Kitasan Black (Umamusume Pretty Derby)": 67,
118
+ "樱花千代王 Sakura Chiyono O (Umamusume Pretty Derby)": 68,
119
+ "天狼星象征 Sirius Symboli (Umamusume Pretty Derby)": 69,
120
+ "目白阿尔丹 Mejiro Ardan (Umamusume Pretty Derby)": 70,
121
+ "八重无敌 Yaeno Muteki (Umamusume Pretty Derby)": 71,
122
+ "鹤丸刚志 Tsurumaru Tsuyoshi (Umamusume Pretty Derby)": 72,
123
+ "目白光明 Mejiro Bright (Umamusume Pretty Derby)": 73,
124
+ "樱花桂冠 Sakura Laurel (Umamusume Pretty Derby)": 74,
125
+ "成田路 Narita Top Road (Umamusume Pretty Derby)": 75,
126
+ "也文摄辉 Yamanin Zephyr (Umamusume Pretty Derby)": 76,
127
+ "真弓快车 Aston Machan (Umamusume Pretty Derby)": 80,
128
+ "骏川手纲 Hayakawa Tazuna (Umamusume Pretty Derby)": 81,
129
+ "小林历奇 Kopano Rickey (Umamusume Pretty Derby)": 83,
130
+ "奇锐骏 Wonder Acute (Umamusume Pretty Derby)": 85,
131
+ "秋川理事长 President Akikawa (Umamusume Pretty Derby)": 86,
132
+ "綾地 寧々 Ayachi Nene (Sanoba Witch)": 87,
133
+ "因幡 めぐる Inaba Meguru (Sanoba Witch)": 88,
134
+ "椎葉 紬 Shiiba Tsumugi (Sanoba Witch)": 89,
135
+ "仮屋 和奏 Kariya Wakama (Sanoba Witch)": 90,
136
+ "戸隠 憧子 Togakushi Touko (Sanoba Witch)": 91,
137
+ "九条裟罗 Kujou Sara (Genshin Impact)": 92,
138
+ "芭芭拉 Barbara (Genshin Impact)": 93,
139
+ "派蒙 Paimon (Genshin Impact)": 94,
140
+ "荒泷一斗 Arataki Itto (Genshin Impact)": 96,
141
+ "早柚 Sayu (Genshin Impact)": 97,
142
+ "香菱 Xiangling (Genshin Impact)": 98,
143
+ "神里绫华 Kamisato Ayaka (Genshin Impact)": 99,
144
+ "重云 Chongyun (Genshin Impact)": 100,
145
+ "流浪者 Wanderer (Genshin Impact)": 102,
146
+ "优菈 Eula (Genshin Impact)": 103,
147
+ "凝光 Ningguang (Genshin Impact)": 105,
148
+ "钟离 Zhongli (Genshin Impact)": 106,
149
+ "雷电将军 Raiden Shogun (Genshin Impact)": 107,
150
+ "枫原万叶 Kaedehara Kazuha (Genshin Impact)": 108,
151
+ "赛诺 Cyno (Genshin Impact)": 109,
152
+ "诺艾尔 Noelle (Genshin Impact)": 112,
153
+ "八重神子 Yae Miko (Genshin Impact)": 113,
154
+ "凯亚 Kaeya (Genshin Impact)": 114,
155
+ "魈 Xiao (Genshin Impact)": 115,
156
+ "托马 Thoma (Genshin Impact)": 116,
157
+ "可莉 Klee (Genshin Impact)": 117,
158
+ "迪卢克 Diluc (Genshin Impact)": 120,
159
+ "夜兰 Yelan (Genshin Impact)": 121,
160
+ "鹿野院平藏 Shikanoin Heizou (Genshin Impact)": 123,
161
+ "辛焱 Xinyan (Genshin Impact)": 124,
162
+ "丽莎 Lisa (Genshin Impact)": 125,
163
+ "云堇 Yun Jin (Genshin Impact)": 126,
164
+ "坎蒂丝 Candace (Genshin Impact)": 127,
165
+ "罗莎莉亚 Rosaria (Genshin Impact)": 128,
166
+ "北斗 Beidou (Genshin Impact)": 129,
167
+ "珊瑚宫心海 Sangonomiya Kokomi (Genshin Impact)": 132,
168
+ "烟绯 Yanfei (Genshin Impact)": 133,
169
+ "久岐忍 Kuki Shinobu (Genshin Impact)": 136,
170
+ "宵宫 Yoimiya (Genshin Impact)": 139,
171
+ "安柏 Amber (Genshin Impact)": 143,
172
+ "迪奥娜 Diona (Genshin Impact)": 144,
173
+ "班尼特 Bennett (Genshin Impact)": 146,
174
+ "雷泽 Razor (Genshin Impact)": 147,
175
+ "阿贝多 Albedo (Genshin Impact)": 151,
176
+ "温迪 Venti (Genshin Impact)": 152,
177
+ "空 Player Male (Genshin Impact)": 153,
178
+ "神里绫人 Kamisato Ayato (Genshin Impact)": 154,
179
+ "琴 Jean (Genshin Impact)": 155,
180
+ "艾尔海森 Alhaitham (Genshin Impact)": 156,
181
+ "莫娜 Mona (Genshin Impact)": 157,
182
+ "妮露 Nilou (Genshin Impact)": 159,
183
+ "胡桃 Hu Tao (Genshin Impact)": 160,
184
+ "甘雨 Ganyu (Genshin Impact)": 161,
185
+ "纳西妲 Nahida (Genshin Impact)": 162,
186
+ "刻晴 Keqing (Genshin Impact)": 165,
187
+ "荧 Player Female (Genshin Impact)": 169,
188
+ "埃洛伊 Aloy (Genshin Impact)": 179,
189
+ "柯莱 Collei (Genshin Impact)": 182,
190
+ "多莉 Dori (Genshin Impact)": 184,
191
+ "提纳里 Tighnari (Genshin Impact)": 186,
192
+ "砂糖 Sucrose (Genshin Impact)": 188,
193
+ "行秋 Xingqiu (Genshin Impact)": 190,
194
+ "奥兹 Oz (Genshin Impact)": 193,
195
+ "五郎 Gorou (Genshin Impact)": 198,
196
+ "达达利亚 Tartalia (Genshin Impact)": 202,
197
+ "七七 Qiqi (Genshin Impact)": 207,
198
+ "申鹤 Shenhe (Genshin Impact)": 217,
199
+ "莱依拉 Layla (Genshin Impact)": 228,
200
+ "菲谢尔 Fishl (Genshin Impact)": 230
201
+ }
202
+ }
data_utils.py ADDED
@@ -0,0 +1,393 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ import os
3
+ import random
4
+ import numpy as np
5
+ import torch
6
+ import torch.utils.data
7
+
8
+ import commons
9
+ from mel_processing import spectrogram_torch
10
+ from utils import load_wav_to_torch, load_filepaths_and_text
11
+ from text import text_to_sequence, cleaned_text_to_sequence
12
+
13
+
14
+ class TextAudioLoader(torch.utils.data.Dataset):
15
+ """
16
+ 1) loads audio, text pairs
17
+ 2) normalizes text and converts them to sequences of integers
18
+ 3) computes spectrograms from audio files.
19
+ """
20
+ def __init__(self, audiopaths_and_text, hparams):
21
+ self.audiopaths_and_text = load_filepaths_and_text(audiopaths_and_text)
22
+ self.text_cleaners = hparams.text_cleaners
23
+ self.max_wav_value = hparams.max_wav_value
24
+ self.sampling_rate = hparams.sampling_rate
25
+ self.filter_length = hparams.filter_length
26
+ self.hop_length = hparams.hop_length
27
+ self.win_length = hparams.win_length
28
+ self.sampling_rate = hparams.sampling_rate
29
+
30
+ self.cleaned_text = getattr(hparams, "cleaned_text", False)
31
+
32
+ self.add_blank = hparams.add_blank
33
+ self.min_text_len = getattr(hparams, "min_text_len", 1)
34
+ self.max_text_len = getattr(hparams, "max_text_len", 190)
35
+
36
+ random.seed(1234)
37
+ random.shuffle(self.audiopaths_and_text)
38
+ self._filter()
39
+
40
+
41
+ def _filter(self):
42
+ """
43
+ Filter text & store spec lengths
44
+ """
45
+ # Store spectrogram lengths for Bucketing
46
+ # wav_length ~= file_size / (wav_channels * Bytes per dim) = file_size / (1 * 2)
47
+ # spec_length = wav_length // hop_length
48
+
49
+ audiopaths_and_text_new = []
50
+ lengths = []
51
+ for audiopath, text in self.audiopaths_and_text:
52
+ if self.min_text_len <= len(text) and len(text) <= self.max_text_len:
53
+ audiopaths_and_text_new.append([audiopath, text])
54
+ lengths.append(os.path.getsize(audiopath) // (2 * self.hop_length))
55
+ self.audiopaths_and_text = audiopaths_and_text_new
56
+ self.lengths = lengths
57
+
58
+ def get_audio_text_pair(self, audiopath_and_text):
59
+ # separate filename and text
60
+ audiopath, text = audiopath_and_text[0], audiopath_and_text[1]
61
+ text = self.get_text(text)
62
+ spec, wav = self.get_audio(audiopath)
63
+ return (text, spec, wav)
64
+
65
+ def get_audio(self, filename):
66
+ audio, sampling_rate = load_wav_to_torch(filename)
67
+ if sampling_rate != self.sampling_rate:
68
+ raise ValueError("{} {} SR doesn't match target {} SR".format(
69
+ sampling_rate, self.sampling_rate))
70
+ audio_norm = audio / self.max_wav_value
71
+ audio_norm = audio_norm.unsqueeze(0)
72
+ spec_filename = filename.replace(".wav", ".spec.pt")
73
+ if os.path.exists(spec_filename):
74
+ spec = torch.load(spec_filename)
75
+ else:
76
+ spec = spectrogram_torch(audio_norm, self.filter_length,
77
+ self.sampling_rate, self.hop_length, self.win_length,
78
+ center=False)
79
+ spec = torch.squeeze(spec, 0)
80
+ torch.save(spec, spec_filename)
81
+ return spec, audio_norm
82
+
83
+ def get_text(self, text):
84
+ if self.cleaned_text:
85
+ text_norm = cleaned_text_to_sequence(text)
86
+ else:
87
+ text_norm = text_to_sequence(text, self.text_cleaners)
88
+ if self.add_blank:
89
+ text_norm = commons.intersperse(text_norm, 0)
90
+ text_norm = torch.LongTensor(text_norm)
91
+ return text_norm
92
+
93
+ def __getitem__(self, index):
94
+ return self.get_audio_text_pair(self.audiopaths_and_text[index])
95
+
96
+ def __len__(self):
97
+ return len(self.audiopaths_and_text)
98
+
99
+
100
+ class TextAudioCollate():
101
+ """ Zero-pads model inputs and targets
102
+ """
103
+ def __init__(self, return_ids=False):
104
+ self.return_ids = return_ids
105
+
106
+ def __call__(self, batch):
107
+ """Collate's training batch from normalized text and aduio
108
+ PARAMS
109
+ ------
110
+ batch: [text_normalized, spec_normalized, wav_normalized]
111
+ """
112
+ # Right zero-pad all one-hot text sequences to max input length
113
+ _, ids_sorted_decreasing = torch.sort(
114
+ torch.LongTensor([x[1].size(1) for x in batch]),
115
+ dim=0, descending=True)
116
+
117
+ max_text_len = max([len(x[0]) for x in batch])
118
+ max_spec_len = max([x[1].size(1) for x in batch])
119
+ max_wav_len = max([x[2].size(1) for x in batch])
120
+
121
+ text_lengths = torch.LongTensor(len(batch))
122
+ spec_lengths = torch.LongTensor(len(batch))
123
+ wav_lengths = torch.LongTensor(len(batch))
124
+
125
+ text_padded = torch.LongTensor(len(batch), max_text_len)
126
+ spec_padded = torch.FloatTensor(len(batch), batch[0][1].size(0), max_spec_len)
127
+ wav_padded = torch.FloatTensor(len(batch), 1, max_wav_len)
128
+ text_padded.zero_()
129
+ spec_padded.zero_()
130
+ wav_padded.zero_()
131
+ for i in range(len(ids_sorted_decreasing)):
132
+ row = batch[ids_sorted_decreasing[i]]
133
+
134
+ text = row[0]
135
+ text_padded[i, :text.size(0)] = text
136
+ text_lengths[i] = text.size(0)
137
+
138
+ spec = row[1]
139
+ spec_padded[i, :, :spec.size(1)] = spec
140
+ spec_lengths[i] = spec.size(1)
141
+
142
+ wav = row[2]
143
+ wav_padded[i, :, :wav.size(1)] = wav
144
+ wav_lengths[i] = wav.size(1)
145
+
146
+ if self.return_ids:
147
+ return text_padded, text_lengths, spec_padded, spec_lengths, wav_padded, wav_lengths, ids_sorted_decreasing
148
+ return text_padded, text_lengths, spec_padded, spec_lengths, wav_padded, wav_lengths
149
+
150
+
151
+ """Multi speaker version"""
152
+ class TextAudioSpeakerLoader(torch.utils.data.Dataset):
153
+ """
154
+ 1) loads audio, speaker_id, text pairs
155
+ 2) normalizes text and converts them to sequences of integers
156
+ 3) computes spectrograms from audio files.
157
+ """
158
+ def __init__(self, audiopaths_sid_text, hparams):
159
+ self.audiopaths_sid_text = load_filepaths_and_text(audiopaths_sid_text)
160
+ self.text_cleaners = hparams.text_cleaners
161
+ self.max_wav_value = hparams.max_wav_value
162
+ self.sampling_rate = hparams.sampling_rate
163
+ self.filter_length = hparams.filter_length
164
+ self.hop_length = hparams.hop_length
165
+ self.win_length = hparams.win_length
166
+ self.sampling_rate = hparams.sampling_rate
167
+
168
+ self.cleaned_text = getattr(hparams, "cleaned_text", False)
169
+
170
+ self.add_blank = hparams.add_blank
171
+ self.min_text_len = getattr(hparams, "min_text_len", 1)
172
+ self.max_text_len = getattr(hparams, "max_text_len", 190)
173
+
174
+ random.seed(1234)
175
+ random.shuffle(self.audiopaths_sid_text)
176
+ self._filter()
177
+
178
+ def _filter(self):
179
+ """
180
+ Filter text & store spec lengths
181
+ """
182
+ # Store spectrogram lengths for Bucketing
183
+ # wav_length ~= file_size / (wav_channels * Bytes per dim) = file_size / (1 * 2)
184
+ # spec_length = wav_length // hop_length
185
+
186
+ audiopaths_sid_text_new = []
187
+ lengths = []
188
+ for audiopath, sid, text in self.audiopaths_sid_text:
189
+ audiopath = "E:/uma_voice/" + audiopath
190
+ if self.min_text_len <= len(text) and len(text) <= self.max_text_len:
191
+ audiopaths_sid_text_new.append([audiopath, sid, text])
192
+ lengths.append(os.path.getsize(audiopath) // (2 * self.hop_length))
193
+ self.audiopaths_sid_text = audiopaths_sid_text_new
194
+ self.lengths = lengths
195
+
196
+ def get_audio_text_speaker_pair(self, audiopath_sid_text):
197
+ # separate filename, speaker_id and text
198
+ audiopath, sid, text = audiopath_sid_text[0], audiopath_sid_text[1], audiopath_sid_text[2]
199
+ text = self.get_text(text)
200
+ spec, wav = self.get_audio(audiopath)
201
+ sid = self.get_sid(sid)
202
+ return (text, spec, wav, sid)
203
+
204
+ def get_audio(self, filename):
205
+ audio, sampling_rate = load_wav_to_torch(filename)
206
+ if sampling_rate != self.sampling_rate:
207
+ raise ValueError("{} {} SR doesn't match target {} SR".format(
208
+ sampling_rate, self.sampling_rate))
209
+ audio_norm = audio / self.max_wav_value
210
+ audio_norm = audio_norm.unsqueeze(0)
211
+ spec_filename = filename.replace(".wav", ".spec.pt")
212
+ if os.path.exists(spec_filename):
213
+ spec = torch.load(spec_filename)
214
+ else:
215
+ spec = spectrogram_torch(audio_norm, self.filter_length,
216
+ self.sampling_rate, self.hop_length, self.win_length,
217
+ center=False)
218
+ spec = torch.squeeze(spec, 0)
219
+ torch.save(spec, spec_filename)
220
+ return spec, audio_norm
221
+
222
+ def get_text(self, text):
223
+ if self.cleaned_text:
224
+ text_norm = cleaned_text_to_sequence(text)
225
+ else:
226
+ text_norm = text_to_sequence(text, self.text_cleaners)
227
+ if self.add_blank:
228
+ text_norm = commons.intersperse(text_norm, 0)
229
+ text_norm = torch.LongTensor(text_norm)
230
+ return text_norm
231
+
232
+ def get_sid(self, sid):
233
+ sid = torch.LongTensor([int(sid)])
234
+ return sid
235
+
236
+ def __getitem__(self, index):
237
+ return self.get_audio_text_speaker_pair(self.audiopaths_sid_text[index])
238
+
239
+ def __len__(self):
240
+ return len(self.audiopaths_sid_text)
241
+
242
+
243
+ class TextAudioSpeakerCollate():
244
+ """ Zero-pads model inputs and targets
245
+ """
246
+ def __init__(self, return_ids=False):
247
+ self.return_ids = return_ids
248
+
249
+ def __call__(self, batch):
250
+ """Collate's training batch from normalized text, audio and speaker identities
251
+ PARAMS
252
+ ------
253
+ batch: [text_normalized, spec_normalized, wav_normalized, sid]
254
+ """
255
+ # Right zero-pad all one-hot text sequences to max input length
256
+ _, ids_sorted_decreasing = torch.sort(
257
+ torch.LongTensor([x[1].size(1) for x in batch]),
258
+ dim=0, descending=True)
259
+
260
+ max_text_len = max([len(x[0]) for x in batch])
261
+ max_spec_len = max([x[1].size(1) for x in batch])
262
+ max_wav_len = max([x[2].size(1) for x in batch])
263
+
264
+ text_lengths = torch.LongTensor(len(batch))
265
+ spec_lengths = torch.LongTensor(len(batch))
266
+ wav_lengths = torch.LongTensor(len(batch))
267
+ sid = torch.LongTensor(len(batch))
268
+
269
+ text_padded = torch.LongTensor(len(batch), max_text_len)
270
+ spec_padded = torch.FloatTensor(len(batch), batch[0][1].size(0), max_spec_len)
271
+ wav_padded = torch.FloatTensor(len(batch), 1, max_wav_len)
272
+ text_padded.zero_()
273
+ spec_padded.zero_()
274
+ wav_padded.zero_()
275
+ for i in range(len(ids_sorted_decreasing)):
276
+ row = batch[ids_sorted_decreasing[i]]
277
+
278
+ text = row[0]
279
+ text_padded[i, :text.size(0)] = text
280
+ text_lengths[i] = text.size(0)
281
+
282
+ spec = row[1]
283
+ spec_padded[i, :, :spec.size(1)] = spec
284
+ spec_lengths[i] = spec.size(1)
285
+
286
+ wav = row[2]
287
+ wav_padded[i, :, :wav.size(1)] = wav
288
+ wav_lengths[i] = wav.size(1)
289
+
290
+ sid[i] = row[3]
291
+
292
+ if self.return_ids:
293
+ return text_padded, text_lengths, spec_padded, spec_lengths, wav_padded, wav_lengths, sid, ids_sorted_decreasing
294
+ return text_padded, text_lengths, spec_padded, spec_lengths, wav_padded, wav_lengths, sid
295
+
296
+
297
+ class DistributedBucketSampler(torch.utils.data.distributed.DistributedSampler):
298
+ """
299
+ Maintain similar input lengths in a batch.
300
+ Length groups are specified by boundaries.
301
+ Ex) boundaries = [b1, b2, b3] -> any batch is included either {x | b1 < length(x) <=b2} or {x | b2 < length(x) <= b3}.
302
+
303
+ It removes samples which are not included in the boundaries.
304
+ Ex) boundaries = [b1, b2, b3] -> any x s.t. length(x) <= b1 or length(x) > b3 are discarded.
305
+ """
306
+ def __init__(self, dataset, batch_size, boundaries, num_replicas=None, rank=None, shuffle=True):
307
+ super().__init__(dataset, num_replicas=num_replicas, rank=rank, shuffle=shuffle)
308
+ self.lengths = dataset.lengths
309
+ self.batch_size = batch_size
310
+ self.boundaries = boundaries
311
+
312
+ self.buckets, self.num_samples_per_bucket = self._create_buckets()
313
+ self.total_size = sum(self.num_samples_per_bucket)
314
+ self.num_samples = self.total_size // self.num_replicas
315
+
316
+ def _create_buckets(self):
317
+ buckets = [[] for _ in range(len(self.boundaries) - 1)]
318
+ for i in range(len(self.lengths)):
319
+ length = self.lengths[i]
320
+ idx_bucket = self._bisect(length)
321
+ if idx_bucket != -1:
322
+ buckets[idx_bucket].append(i)
323
+
324
+ for i in range(len(buckets) - 1, 0, -1):
325
+ if len(buckets[i]) == 0:
326
+ buckets.pop(i)
327
+ self.boundaries.pop(i+1)
328
+
329
+ num_samples_per_bucket = []
330
+ for i in range(len(buckets)):
331
+ len_bucket = len(buckets[i])
332
+ total_batch_size = self.num_replicas * self.batch_size
333
+ rem = (total_batch_size - (len_bucket % total_batch_size)) % total_batch_size
334
+ num_samples_per_bucket.append(len_bucket + rem)
335
+ return buckets, num_samples_per_bucket
336
+
337
+ def __iter__(self):
338
+ # deterministically shuffle based on epoch
339
+ g = torch.Generator()
340
+ g.manual_seed(self.epoch)
341
+
342
+ indices = []
343
+ if self.shuffle:
344
+ for bucket in self.buckets:
345
+ indices.append(torch.randperm(len(bucket), generator=g).tolist())
346
+ else:
347
+ for bucket in self.buckets:
348
+ indices.append(list(range(len(bucket))))
349
+
350
+ batches = []
351
+ for i in range(len(self.buckets)):
352
+ bucket = self.buckets[i]
353
+ len_bucket = len(bucket)
354
+ ids_bucket = indices[i]
355
+ num_samples_bucket = self.num_samples_per_bucket[i]
356
+
357
+ # add extra samples to make it evenly divisible
358
+ rem = num_samples_bucket - len_bucket
359
+ ids_bucket = ids_bucket + ids_bucket * (rem // len_bucket) + ids_bucket[:(rem % len_bucket)]
360
+
361
+ # subsample
362
+ ids_bucket = ids_bucket[self.rank::self.num_replicas]
363
+
364
+ # batching
365
+ for j in range(len(ids_bucket) // self.batch_size):
366
+ batch = [bucket[idx] for idx in ids_bucket[j*self.batch_size:(j+1)*self.batch_size]]
367
+ batches.append(batch)
368
+
369
+ if self.shuffle:
370
+ batch_ids = torch.randperm(len(batches), generator=g).tolist()
371
+ batches = [batches[i] for i in batch_ids]
372
+ self.batches = batches
373
+
374
+ assert len(self.batches) * self.batch_size == self.num_samples
375
+ return iter(self.batches)
376
+
377
+ def _bisect(self, x, lo=0, hi=None):
378
+ if hi is None:
379
+ hi = len(self.boundaries) - 1
380
+
381
+ if hi > lo:
382
+ mid = (hi + lo) // 2
383
+ if self.boundaries[mid] < x and x <= self.boundaries[mid+1]:
384
+ return mid
385
+ elif x <= self.boundaries[mid]:
386
+ return self._bisect(x, lo, mid)
387
+ else:
388
+ return self._bisect(x, mid + 1, hi)
389
+ else:
390
+ return -1
391
+
392
+ def __len__(self):
393
+ return self.num_samples // self.batch_size
hubert_model.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ from typing import Optional, Tuple
3
+ import random
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+ import torch.nn.functional as F
8
+ from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
9
+
10
+ class Hubert(nn.Module):
11
+ def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
12
+ super().__init__()
13
+ self._mask = mask
14
+ self.feature_extractor = FeatureExtractor()
15
+ self.feature_projection = FeatureProjection()
16
+ self.positional_embedding = PositionalConvEmbedding()
17
+ self.norm = nn.LayerNorm(768)
18
+ self.dropout = nn.Dropout(0.1)
19
+ self.encoder = TransformerEncoder(
20
+ nn.TransformerEncoderLayer(
21
+ 768, 12, 3072, activation="gelu", batch_first=True
22
+ ),
23
+ 12,
24
+ )
25
+ self.proj = nn.Linear(768, 256)
26
+
27
+ self.masked_spec_embed = nn.Parameter(torch.FloatTensor(768).uniform_())
28
+ self.label_embedding = nn.Embedding(num_label_embeddings, 256)
29
+
30
+ def mask(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
31
+ mask = None
32
+ if self.training and self._mask:
33
+ mask = _compute_mask((x.size(0), x.size(1)), 0.8, 10, x.device, 2)
34
+ x[mask] = self.masked_spec_embed.to(x.dtype)
35
+ return x, mask
36
+
37
+ def encode(
38
+ self, x: torch.Tensor, layer: Optional[int] = None
39
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
40
+ x = self.feature_extractor(x)
41
+ x = self.feature_projection(x.transpose(1, 2))
42
+ x, mask = self.mask(x)
43
+ x = x + self.positional_embedding(x)
44
+ x = self.dropout(self.norm(x))
45
+ x = self.encoder(x, output_layer=layer)
46
+ return x, mask
47
+
48
+ def logits(self, x: torch.Tensor) -> torch.Tensor:
49
+ logits = torch.cosine_similarity(
50
+ x.unsqueeze(2),
51
+ self.label_embedding.weight.unsqueeze(0).unsqueeze(0),
52
+ dim=-1,
53
+ )
54
+ return logits / 0.1
55
+
56
+ def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
57
+ x, mask = self.encode(x)
58
+ x = self.proj(x)
59
+ logits = self.logits(x)
60
+ return logits, mask
61
+
62
+
63
+ class HubertSoft(Hubert):
64
+ def __init__(self):
65
+ super().__init__()
66
+
67
+ @torch.inference_mode()
68
+ def units(self, wav: torch.Tensor) -> torch.Tensor:
69
+ wav = F.pad(wav, ((400 - 320) // 2, (400 - 320) // 2))
70
+ x, _ = self.encode(wav)
71
+ return self.proj(x)
72
+
73
+
74
+ class FeatureExtractor(nn.Module):
75
+ def __init__(self):
76
+ super().__init__()
77
+ self.conv0 = nn.Conv1d(1, 512, 10, 5, bias=False)
78
+ self.norm0 = nn.GroupNorm(512, 512)
79
+ self.conv1 = nn.Conv1d(512, 512, 3, 2, bias=False)
80
+ self.conv2 = nn.Conv1d(512, 512, 3, 2, bias=False)
81
+ self.conv3 = nn.Conv1d(512, 512, 3, 2, bias=False)
82
+ self.conv4 = nn.Conv1d(512, 512, 3, 2, bias=False)
83
+ self.conv5 = nn.Conv1d(512, 512, 2, 2, bias=False)
84
+ self.conv6 = nn.Conv1d(512, 512, 2, 2, bias=False)
85
+
86
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
87
+ x = F.gelu(self.norm0(self.conv0(x)))
88
+ x = F.gelu(self.conv1(x))
89
+ x = F.gelu(self.conv2(x))
90
+ x = F.gelu(self.conv3(x))
91
+ x = F.gelu(self.conv4(x))
92
+ x = F.gelu(self.conv5(x))
93
+ x = F.gelu(self.conv6(x))
94
+ return x
95
+
96
+
97
+ class FeatureProjection(nn.Module):
98
+ def __init__(self):
99
+ super().__init__()
100
+ self.norm = nn.LayerNorm(512)
101
+ self.projection = nn.Linear(512, 768)
102
+ self.dropout = nn.Dropout(0.1)
103
+
104
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
105
+ x = self.norm(x)
106
+ x = self.projection(x)
107
+ x = self.dropout(x)
108
+ return x
109
+
110
+
111
+ class PositionalConvEmbedding(nn.Module):
112
+ def __init__(self):
113
+ super().__init__()
114
+ self.conv = nn.Conv1d(
115
+ 768,
116
+ 768,
117
+ kernel_size=128,
118
+ padding=128 // 2,
119
+ groups=16,
120
+ )
121
+ self.conv = nn.utils.weight_norm(self.conv, name="weight", dim=2)
122
+
123
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
124
+ x = self.conv(x.transpose(1, 2))
125
+ x = F.gelu(x[:, :, :-1])
126
+ return x.transpose(1, 2)
127
+
128
+
129
+ class TransformerEncoder(nn.Module):
130
+ def __init__(
131
+ self, encoder_layer: nn.TransformerEncoderLayer, num_layers: int
132
+ ) -> None:
133
+ super(TransformerEncoder, self).__init__()
134
+ self.layers = nn.ModuleList(
135
+ [copy.deepcopy(encoder_layer) for _ in range(num_layers)]
136
+ )
137
+ self.num_layers = num_layers
138
+
139
+ def forward(
140
+ self,
141
+ src: torch.Tensor,
142
+ mask: torch.Tensor = None,
143
+ src_key_padding_mask: torch.Tensor = None,
144
+ output_layer: Optional[int] = None,
145
+ ) -> torch.Tensor:
146
+ output = src
147
+ for layer in self.layers[:output_layer]:
148
+ output = layer(
149
+ output, src_mask=mask, src_key_padding_mask=src_key_padding_mask
150
+ )
151
+ return output
152
+
153
+
154
+ def _compute_mask(
155
+ shape: Tuple[int, int],
156
+ mask_prob: float,
157
+ mask_length: int,
158
+ device: torch.device,
159
+ min_masks: int = 0,
160
+ ) -> torch.Tensor:
161
+ batch_size, sequence_length = shape
162
+
163
+ if mask_length < 1:
164
+ raise ValueError("`mask_length` has to be bigger than 0.")
165
+
166
+ if mask_length > sequence_length:
167
+ raise ValueError(
168
+ f"`mask_length` has to be smaller than `sequence_length`, but got `mask_length`: {mask_length} and `sequence_length`: {sequence_length}`"
169
+ )
170
+
171
+ # compute number of masked spans in batch
172
+ num_masked_spans = int(mask_prob * sequence_length / mask_length + random.random())
173
+ num_masked_spans = max(num_masked_spans, min_masks)
174
+
175
+ # make sure num masked indices <= sequence_length
176
+ if num_masked_spans * mask_length > sequence_length:
177
+ num_masked_spans = sequence_length // mask_length
178
+
179
+ # SpecAugment mask to fill
180
+ mask = torch.zeros((batch_size, sequence_length), device=device, dtype=torch.bool)
181
+
182
+ # uniform distribution to sample from, make sure that offset samples are < sequence_length
183
+ uniform_dist = torch.ones(
184
+ (batch_size, sequence_length - (mask_length - 1)), device=device
185
+ )
186
+
187
+ # get random indices to mask
188
+ mask_indices = torch.multinomial(uniform_dist, num_masked_spans)
189
+
190
+ # expand masked indices to masked spans
191
+ mask_indices = (
192
+ mask_indices.unsqueeze(dim=-1)
193
+ .expand((batch_size, num_masked_spans, mask_length))
194
+ .reshape(batch_size, num_masked_spans * mask_length)
195
+ )
196
+ offsets = (
197
+ torch.arange(mask_length, device=device)[None, None, :]
198
+ .expand((batch_size, num_masked_spans, mask_length))
199
+ .reshape(batch_size, num_masked_spans * mask_length)
200
+ )
201
+ mask_idxs = mask_indices + offsets
202
+
203
+ # scatter indices to mask
204
+ mask = mask.scatter(1, mask_idxs, True)
205
+
206
+ return mask
207
+
208
+
209
+ def hubert_soft(
210
+ path: str
211
+ ) -> HubertSoft:
212
+ r"""HuBERT-Soft from `"A Comparison of Discrete and Soft Speech Units for Improved Voice Conversion"`.
213
+ Args:
214
+ path (str): path of a pretrained model
215
+ """
216
+ hubert = HubertSoft()
217
+ checkpoint = torch.load(path)
218
+ consume_prefix_in_state_dict_if_present(checkpoint, "module.")
219
+ hubert.load_state_dict(checkpoint)
220
+ hubert.eval()
221
+ return hubert
jieba/dict.txt ADDED
The diff for this file is too large to render. See raw diff
 
losses.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch.nn import functional as F
3
+
4
+ import commons
5
+
6
+
7
+ def feature_loss(fmap_r, fmap_g):
8
+ loss = 0
9
+ for dr, dg in zip(fmap_r, fmap_g):
10
+ for rl, gl in zip(dr, dg):
11
+ rl = rl.float().detach()
12
+ gl = gl.float()
13
+ loss += torch.mean(torch.abs(rl - gl))
14
+
15
+ return loss * 2
16
+
17
+
18
+ def discriminator_loss(disc_real_outputs, disc_generated_outputs):
19
+ loss = 0
20
+ r_losses = []
21
+ g_losses = []
22
+ for dr, dg in zip(disc_real_outputs, disc_generated_outputs):
23
+ dr = dr.float()
24
+ dg = dg.float()
25
+ r_loss = torch.mean((1-dr)**2)
26
+ g_loss = torch.mean(dg**2)
27
+ loss += (r_loss + g_loss)
28
+ r_losses.append(r_loss.item())
29
+ g_losses.append(g_loss.item())
30
+
31
+ return loss, r_losses, g_losses
32
+
33
+
34
+ def generator_loss(disc_outputs):
35
+ loss = 0
36
+ gen_losses = []
37
+ for dg in disc_outputs:
38
+ dg = dg.float()
39
+ l = torch.mean((1-dg)**2)
40
+ gen_losses.append(l)
41
+ loss += l
42
+
43
+ return loss, gen_losses
44
+
45
+
46
+ def kl_loss(z_p, logs_q, m_p, logs_p, z_mask):
47
+ """
48
+ z_p, logs_q: [b, h, t_t]
49
+ m_p, logs_p: [b, h, t_t]
50
+ """
51
+ z_p = z_p.float()
52
+ logs_q = logs_q.float()
53
+ m_p = m_p.float()
54
+ logs_p = logs_p.float()
55
+ z_mask = z_mask.float()
56
+
57
+ kl = logs_p - logs_q - 0.5
58
+ kl += 0.5 * ((z_p - m_p)**2) * torch.exp(-2. * logs_p)
59
+ kl = torch.sum(kl * z_mask)
60
+ l = kl / torch.sum(z_mask)
61
+ return l
mel_processing.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.utils.data
3
+ from librosa.filters import mel as librosa_mel_fn
4
+
5
+ MAX_WAV_VALUE = 32768.0
6
+
7
+
8
+ def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):
9
+ """
10
+ PARAMS
11
+ ------
12
+ C: compression factor
13
+ """
14
+ return torch.log(torch.clamp(x, min=clip_val) * C)
15
+
16
+
17
+ def dynamic_range_decompression_torch(x, C=1):
18
+ """
19
+ PARAMS
20
+ ------
21
+ C: compression factor used to compress
22
+ """
23
+ return torch.exp(x) / C
24
+
25
+
26
+ def spectral_normalize_torch(magnitudes):
27
+ output = dynamic_range_compression_torch(magnitudes)
28
+ return output
29
+
30
+
31
+ def spectral_de_normalize_torch(magnitudes):
32
+ output = dynamic_range_decompression_torch(magnitudes)
33
+ return output
34
+
35
+
36
+ mel_basis = {}
37
+ hann_window = {}
38
+
39
+
40
+ def spectrogram_torch(y, n_fft, sampling_rate, hop_size, win_size, center=False):
41
+ if torch.min(y) < -1.:
42
+ print('min value is ', torch.min(y))
43
+ if torch.max(y) > 1.:
44
+ print('max value is ', torch.max(y))
45
+
46
+ global hann_window
47
+ dtype_device = str(y.dtype) + '_' + str(y.device)
48
+ wnsize_dtype_device = str(win_size) + '_' + dtype_device
49
+ if wnsize_dtype_device not in hann_window:
50
+ hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(dtype=y.dtype, device=y.device)
51
+
52
+ y = torch.nn.functional.pad(y.unsqueeze(1), (int((n_fft-hop_size)/2), int((n_fft-hop_size)/2)), mode='reflect')
53
+ y = y.squeeze(1)
54
+
55
+ spec = torch.stft(y, n_fft, hop_length=hop_size, win_length=win_size, window=hann_window[wnsize_dtype_device],
56
+ center=center, pad_mode='reflect', normalized=False, onesided=True, return_complex=False)
57
+
58
+ spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)
59
+ return spec
60
+
61
+
62
+ def spec_to_mel_torch(spec, n_fft, num_mels, sampling_rate, fmin, fmax):
63
+ global mel_basis
64
+ dtype_device = str(spec.dtype) + '_' + str(spec.device)
65
+ fmax_dtype_device = str(fmax) + '_' + dtype_device
66
+ if fmax_dtype_device not in mel_basis:
67
+ mel = librosa_mel_fn(sampling_rate, n_fft, num_mels, fmin, fmax)
68
+ mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(dtype=spec.dtype, device=spec.device)
69
+ spec = torch.matmul(mel_basis[fmax_dtype_device], spec)
70
+ spec = spectral_normalize_torch(spec)
71
+ return spec
72
+
73
+
74
+ def mel_spectrogram_torch(y, n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax, center=False):
75
+ if torch.min(y) < -1.:
76
+ print('min value is ', torch.min(y))
77
+ if torch.max(y) > 1.:
78
+ print('max value is ', torch.max(y))
79
+
80
+ global mel_basis, hann_window
81
+ dtype_device = str(y.dtype) + '_' + str(y.device)
82
+ fmax_dtype_device = str(fmax) + '_' + dtype_device
83
+ wnsize_dtype_device = str(win_size) + '_' + dtype_device
84
+ if fmax_dtype_device not in mel_basis:
85
+ mel = librosa_mel_fn(sampling_rate, n_fft, num_mels, fmin, fmax)
86
+ mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(dtype=y.dtype, device=y.device)
87
+ if wnsize_dtype_device not in hann_window:
88
+ hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(dtype=y.dtype, device=y.device)
89
+
90
+ y = torch.nn.functional.pad(y.unsqueeze(1), (int((n_fft-hop_size)/2), int((n_fft-hop_size)/2)), mode='reflect')
91
+ y = y.squeeze(1)
92
+
93
+ spec = torch.stft(y, n_fft, hop_length=hop_size, win_length=win_size, window=hann_window[wnsize_dtype_device],
94
+ center=center, pad_mode='reflect', normalized=False, onesided=True)
95
+
96
+ spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)
97
+
98
+ spec = torch.matmul(mel_basis[fmax_dtype_device], spec)
99
+ spec = spectral_normalize_torch(spec)
100
+
101
+ return spec
models.py ADDED
@@ -0,0 +1,542 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ from torch import nn
4
+ from torch.nn import functional as F
5
+
6
+ import commons
7
+ import modules
8
+ import attentions
9
+
10
+ from torch.nn import Conv1d, ConvTranspose1d, Conv2d
11
+ from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm
12
+ from commons import init_weights, get_padding
13
+
14
+
15
+ class StochasticDurationPredictor(nn.Module):
16
+ def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, n_flows=4, gin_channels=0):
17
+ super().__init__()
18
+ filter_channels = in_channels # it needs to be removed from future version.
19
+ self.in_channels = in_channels
20
+ self.filter_channels = filter_channels
21
+ self.kernel_size = kernel_size
22
+ self.p_dropout = p_dropout
23
+ self.n_flows = n_flows
24
+ self.gin_channels = gin_channels
25
+
26
+ self.log_flow = modules.Log()
27
+ self.flows = nn.ModuleList()
28
+ self.flows.append(modules.ElementwiseAffine(2))
29
+ for i in range(n_flows):
30
+ self.flows.append(modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3))
31
+ self.flows.append(modules.Flip())
32
+
33
+ self.post_pre = nn.Conv1d(1, filter_channels, 1)
34
+ self.post_proj = nn.Conv1d(filter_channels, filter_channels, 1)
35
+ self.post_convs = modules.DDSConv(filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout)
36
+ self.post_flows = nn.ModuleList()
37
+ self.post_flows.append(modules.ElementwiseAffine(2))
38
+ for i in range(4):
39
+ self.post_flows.append(modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3))
40
+ self.post_flows.append(modules.Flip())
41
+
42
+ self.pre = nn.Conv1d(in_channels, filter_channels, 1)
43
+ self.proj = nn.Conv1d(filter_channels, filter_channels, 1)
44
+ self.convs = modules.DDSConv(filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout)
45
+ if gin_channels != 0:
46
+ self.cond = nn.Conv1d(gin_channels, filter_channels, 1)
47
+
48
+ def forward(self, x, x_mask, w=None, g=None, reverse=False, noise_scale=1.0):
49
+ x = torch.detach(x)
50
+ x = self.pre(x)
51
+ if g is not None:
52
+ g = torch.detach(g)
53
+ x = x + self.cond(g)
54
+ x = self.convs(x, x_mask)
55
+ x = self.proj(x) * x_mask
56
+
57
+ if not reverse:
58
+ flows = self.flows
59
+ assert w is not None
60
+
61
+ logdet_tot_q = 0
62
+ h_w = self.post_pre(w)
63
+ h_w = self.post_convs(h_w, x_mask)
64
+ h_w = self.post_proj(h_w) * x_mask
65
+ e_q = torch.randn(w.size(0), 2, w.size(2)).to(device=x.device, dtype=x.dtype) * x_mask
66
+ z_q = e_q
67
+ for flow in self.post_flows:
68
+ z_q, logdet_q = flow(z_q, x_mask, g=(x + h_w))
69
+ logdet_tot_q += logdet_q
70
+ z_u, z1 = torch.split(z_q, [1, 1], 1)
71
+ u = torch.sigmoid(z_u) * x_mask
72
+ z0 = (w - u) * x_mask
73
+ logdet_tot_q += torch.sum((F.logsigmoid(z_u) + F.logsigmoid(-z_u)) * x_mask, [1,2])
74
+ logq = torch.sum(-0.5 * (math.log(2*math.pi) + (e_q**2)) * x_mask, [1,2]) - logdet_tot_q
75
+
76
+ logdet_tot = 0
77
+ z0, logdet = self.log_flow(z0, x_mask)
78
+ logdet_tot += logdet
79
+ z = torch.cat([z0, z1], 1)
80
+ for flow in flows:
81
+ z, logdet = flow(z, x_mask, g=x, reverse=reverse)
82
+ logdet_tot = logdet_tot + logdet
83
+ nll = torch.sum(0.5 * (math.log(2*math.pi) + (z**2)) * x_mask, [1,2]) - logdet_tot
84
+ return nll + logq # [b]
85
+ else:
86
+ flows = list(reversed(self.flows))
87
+ flows = flows[:-2] + [flows[-1]] # remove a useless vflow
88
+ z = torch.randn(x.size(0), 2, x.size(2)).to(device=x.device, dtype=x.dtype) * noise_scale
89
+ for flow in flows:
90
+ z = flow(z, x_mask, g=x, reverse=reverse)
91
+ z0, z1 = torch.split(z, [1, 1], 1)
92
+ logw = z0
93
+ return logw
94
+
95
+
96
+ class DurationPredictor(nn.Module):
97
+ def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, gin_channels=0):
98
+ super().__init__()
99
+
100
+ self.in_channels = in_channels
101
+ self.filter_channels = filter_channels
102
+ self.kernel_size = kernel_size
103
+ self.p_dropout = p_dropout
104
+ self.gin_channels = gin_channels
105
+
106
+ self.drop = nn.Dropout(p_dropout)
107
+ self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size, padding=kernel_size//2)
108
+ self.norm_1 = modules.LayerNorm(filter_channels)
109
+ self.conv_2 = nn.Conv1d(filter_channels, filter_channels, kernel_size, padding=kernel_size//2)
110
+ self.norm_2 = modules.LayerNorm(filter_channels)
111
+ self.proj = nn.Conv1d(filter_channels, 1, 1)
112
+
113
+ if gin_channels != 0:
114
+ self.cond = nn.Conv1d(gin_channels, in_channels, 1)
115
+
116
+ def forward(self, x, x_mask, g=None):
117
+ x = torch.detach(x)
118
+ if g is not None:
119
+ g = torch.detach(g)
120
+ x = x + self.cond(g)
121
+ x = self.conv_1(x * x_mask)
122
+ x = torch.relu(x)
123
+ x = self.norm_1(x)
124
+ x = self.drop(x)
125
+ x = self.conv_2(x * x_mask)
126
+ x = torch.relu(x)
127
+ x = self.norm_2(x)
128
+ x = self.drop(x)
129
+ x = self.proj(x * x_mask)
130
+ return x * x_mask
131
+
132
+
133
+ class TextEncoder(nn.Module):
134
+ def __init__(self,
135
+ n_vocab,
136
+ out_channels,
137
+ hidden_channels,
138
+ filter_channels,
139
+ n_heads,
140
+ n_layers,
141
+ kernel_size,
142
+ p_dropout,
143
+ emotion_embedding):
144
+ super().__init__()
145
+ self.n_vocab = n_vocab
146
+ self.out_channels = out_channels
147
+ self.hidden_channels = hidden_channels
148
+ self.filter_channels = filter_channels
149
+ self.n_heads = n_heads
150
+ self.n_layers = n_layers
151
+ self.kernel_size = kernel_size
152
+ self.p_dropout = p_dropout
153
+ self.emotion_embedding = emotion_embedding
154
+
155
+ if self.n_vocab!=0:
156
+ self.emb = nn.Embedding(n_vocab, hidden_channels)
157
+ if emotion_embedding:
158
+ self.emotion_emb = nn.Linear(1024, hidden_channels)
159
+ nn.init.normal_(self.emb.weight, 0.0, hidden_channels**-0.5)
160
+
161
+ self.encoder = attentions.Encoder(
162
+ hidden_channels,
163
+ filter_channels,
164
+ n_heads,
165
+ n_layers,
166
+ kernel_size,
167
+ p_dropout)
168
+ self.proj= nn.Conv1d(hidden_channels, out_channels * 2, 1)
169
+
170
+ def forward(self, x, x_lengths, emotion_embedding=None):
171
+ if self.n_vocab!=0:
172
+ x = self.emb(x) * math.sqrt(self.hidden_channels) # [b, t, h]
173
+ if emotion_embedding is not None:
174
+ x = x + self.emotion_emb(emotion_embedding.unsqueeze(1))
175
+ x = torch.transpose(x, 1, -1) # [b, h, t]
176
+ x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
177
+
178
+ x = self.encoder(x * x_mask, x_mask)
179
+ stats = self.proj(x) * x_mask
180
+
181
+ m, logs = torch.split(stats, self.out_channels, dim=1)
182
+ return x, m, logs, x_mask
183
+
184
+
185
+ class ResidualCouplingBlock(nn.Module):
186
+ def __init__(self,
187
+ channels,
188
+ hidden_channels,
189
+ kernel_size,
190
+ dilation_rate,
191
+ n_layers,
192
+ n_flows=4,
193
+ gin_channels=0):
194
+ super().__init__()
195
+ self.channels = channels
196
+ self.hidden_channels = hidden_channels
197
+ self.kernel_size = kernel_size
198
+ self.dilation_rate = dilation_rate
199
+ self.n_layers = n_layers
200
+ self.n_flows = n_flows
201
+ self.gin_channels = gin_channels
202
+
203
+ self.flows = nn.ModuleList()
204
+ for i in range(n_flows):
205
+ self.flows.append(modules.ResidualCouplingLayer(channels, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels, mean_only=True))
206
+ self.flows.append(modules.Flip())
207
+
208
+ def forward(self, x, x_mask, g=None, reverse=False):
209
+ if not reverse:
210
+ for flow in self.flows:
211
+ x, _ = flow(x, x_mask, g=g, reverse=reverse)
212
+ else:
213
+ for flow in reversed(self.flows):
214
+ x = flow(x, x_mask, g=g, reverse=reverse)
215
+ return x
216
+
217
+
218
+ class PosteriorEncoder(nn.Module):
219
+ def __init__(self,
220
+ in_channels,
221
+ out_channels,
222
+ hidden_channels,
223
+ kernel_size,
224
+ dilation_rate,
225
+ n_layers,
226
+ gin_channels=0):
227
+ super().__init__()
228
+ self.in_channels = in_channels
229
+ self.out_channels = out_channels
230
+ self.hidden_channels = hidden_channels
231
+ self.kernel_size = kernel_size
232
+ self.dilation_rate = dilation_rate
233
+ self.n_layers = n_layers
234
+ self.gin_channels = gin_channels
235
+
236
+ self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
237
+ self.enc = modules.WN(hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels)
238
+ self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
239
+
240
+ def forward(self, x, x_lengths, g=None):
241
+ x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
242
+ x = self.pre(x) * x_mask
243
+ x = self.enc(x, x_mask, g=g)
244
+ stats = self.proj(x) * x_mask
245
+ m, logs = torch.split(stats, self.out_channels, dim=1)
246
+ z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask
247
+ return z, m, logs, x_mask
248
+
249
+
250
+ class Generator(torch.nn.Module):
251
+ def __init__(self, initial_channel, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, upsample_initial_channel, upsample_kernel_sizes, gin_channels=0):
252
+ super(Generator, self).__init__()
253
+ self.num_kernels = len(resblock_kernel_sizes)
254
+ self.num_upsamples = len(upsample_rates)
255
+ self.conv_pre = Conv1d(initial_channel, upsample_initial_channel, 7, 1, padding=3)
256
+ resblock = modules.ResBlock1 if resblock == '1' else modules.ResBlock2
257
+
258
+ self.ups = nn.ModuleList()
259
+ for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
260
+ self.ups.append(weight_norm(
261
+ ConvTranspose1d(upsample_initial_channel//(2**i), upsample_initial_channel//(2**(i+1)),
262
+ k, u, padding=(k-u)//2)))
263
+
264
+ self.resblocks = nn.ModuleList()
265
+ for i in range(len(self.ups)):
266
+ ch = upsample_initial_channel//(2**(i+1))
267
+ for j, (k, d) in enumerate(zip(resblock_kernel_sizes, resblock_dilation_sizes)):
268
+ self.resblocks.append(resblock(ch, k, d))
269
+
270
+ self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False)
271
+ self.ups.apply(init_weights)
272
+
273
+ if gin_channels != 0:
274
+ self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
275
+
276
+ def forward(self, x, g=None):
277
+ x = self.conv_pre(x)
278
+ if g is not None:
279
+ x = x + self.cond(g)
280
+
281
+ for i in range(self.num_upsamples):
282
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
283
+ x = self.ups[i](x)
284
+ xs = None
285
+ for j in range(self.num_kernels):
286
+ if xs is None:
287
+ xs = self.resblocks[i*self.num_kernels+j](x)
288
+ else:
289
+ xs += self.resblocks[i*self.num_kernels+j](x)
290
+ x = xs / self.num_kernels
291
+ x = F.leaky_relu(x)
292
+ x = self.conv_post(x)
293
+ x = torch.tanh(x)
294
+
295
+ return x
296
+
297
+ def remove_weight_norm(self):
298
+ print('Removing weight norm...')
299
+ for l in self.ups:
300
+ remove_weight_norm(l)
301
+ for l in self.resblocks:
302
+ l.remove_weight_norm()
303
+
304
+
305
+ class DiscriminatorP(torch.nn.Module):
306
+ def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False):
307
+ super(DiscriminatorP, self).__init__()
308
+ self.period = period
309
+ self.use_spectral_norm = use_spectral_norm
310
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
311
+ self.convs = nn.ModuleList([
312
+ norm_f(Conv2d(1, 32, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
313
+ norm_f(Conv2d(32, 128, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
314
+ norm_f(Conv2d(128, 512, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
315
+ norm_f(Conv2d(512, 1024, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
316
+ norm_f(Conv2d(1024, 1024, (kernel_size, 1), 1, padding=(get_padding(kernel_size, 1), 0))),
317
+ ])
318
+ self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
319
+
320
+ def forward(self, x):
321
+ fmap = []
322
+
323
+ # 1d to 2d
324
+ b, c, t = x.shape
325
+ if t % self.period != 0: # pad first
326
+ n_pad = self.period - (t % self.period)
327
+ x = F.pad(x, (0, n_pad), "reflect")
328
+ t = t + n_pad
329
+ x = x.view(b, c, t // self.period, self.period)
330
+
331
+ for l in self.convs:
332
+ x = l(x)
333
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
334
+ fmap.append(x)
335
+ x = self.conv_post(x)
336
+ fmap.append(x)
337
+ x = torch.flatten(x, 1, -1)
338
+
339
+ return x, fmap
340
+
341
+
342
+ class DiscriminatorS(torch.nn.Module):
343
+ def __init__(self, use_spectral_norm=False):
344
+ super(DiscriminatorS, self).__init__()
345
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
346
+ self.convs = nn.ModuleList([
347
+ norm_f(Conv1d(1, 16, 15, 1, padding=7)),
348
+ norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)),
349
+ norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)),
350
+ norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)),
351
+ norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)),
352
+ norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
353
+ ])
354
+ self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
355
+
356
+ def forward(self, x):
357
+ fmap = []
358
+
359
+ for l in self.convs:
360
+ x = l(x)
361
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
362
+ fmap.append(x)
363
+ x = self.conv_post(x)
364
+ fmap.append(x)
365
+ x = torch.flatten(x, 1, -1)
366
+
367
+ return x, fmap
368
+
369
+
370
+ class MultiPeriodDiscriminator(torch.nn.Module):
371
+ def __init__(self, use_spectral_norm=False):
372
+ super(MultiPeriodDiscriminator, self).__init__()
373
+ periods = [2,3,5,7,11]
374
+
375
+ discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
376
+ discs = discs + [DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods]
377
+ self.discriminators = nn.ModuleList(discs)
378
+
379
+ def forward(self, y, y_hat):
380
+ y_d_rs = []
381
+ y_d_gs = []
382
+ fmap_rs = []
383
+ fmap_gs = []
384
+ for i, d in enumerate(self.discriminators):
385
+ y_d_r, fmap_r = d(y)
386
+ y_d_g, fmap_g = d(y_hat)
387
+ y_d_rs.append(y_d_r)
388
+ y_d_gs.append(y_d_g)
389
+ fmap_rs.append(fmap_r)
390
+ fmap_gs.append(fmap_g)
391
+
392
+ return y_d_rs, y_d_gs, fmap_rs, fmap_gs
393
+
394
+
395
+
396
+ class SynthesizerTrn(nn.Module):
397
+ """
398
+ Synthesizer for Training
399
+ """
400
+
401
+ def __init__(self,
402
+ n_vocab,
403
+ spec_channels,
404
+ segment_size,
405
+ inter_channels,
406
+ hidden_channels,
407
+ filter_channels,
408
+ n_heads,
409
+ n_layers,
410
+ kernel_size,
411
+ p_dropout,
412
+ resblock,
413
+ resblock_kernel_sizes,
414
+ resblock_dilation_sizes,
415
+ upsample_rates,
416
+ upsample_initial_channel,
417
+ upsample_kernel_sizes,
418
+ n_speakers=0,
419
+ gin_channels=0,
420
+ use_sdp=True,
421
+ emotion_embedding=False,
422
+ **kwargs):
423
+
424
+ super().__init__()
425
+ self.n_vocab = n_vocab
426
+ self.spec_channels = spec_channels
427
+ self.inter_channels = inter_channels
428
+ self.hidden_channels = hidden_channels
429
+ self.filter_channels = filter_channels
430
+ self.n_heads = n_heads
431
+ self.n_layers = n_layers
432
+ self.kernel_size = kernel_size
433
+ self.p_dropout = p_dropout
434
+ self.resblock = resblock
435
+ self.resblock_kernel_sizes = resblock_kernel_sizes
436
+ self.resblock_dilation_sizes = resblock_dilation_sizes
437
+ self.upsample_rates = upsample_rates
438
+ self.upsample_initial_channel = upsample_initial_channel
439
+ self.upsample_kernel_sizes = upsample_kernel_sizes
440
+ self.segment_size = segment_size
441
+ self.n_speakers = n_speakers
442
+ self.gin_channels = gin_channels
443
+
444
+ self.use_sdp = use_sdp
445
+
446
+ self.enc_p = TextEncoder(n_vocab,
447
+ inter_channels,
448
+ hidden_channels,
449
+ filter_channels,
450
+ n_heads,
451
+ n_layers,
452
+ kernel_size,
453
+ p_dropout,
454
+ emotion_embedding)
455
+ self.dec = Generator(inter_channels, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, upsample_initial_channel, upsample_kernel_sizes, gin_channels=gin_channels)
456
+ self.enc_q = PosteriorEncoder(spec_channels, inter_channels, hidden_channels, 5, 1, 16, gin_channels=gin_channels)
457
+ self.flow = ResidualCouplingBlock(inter_channels, hidden_channels, 5, 1, 4, gin_channels=gin_channels)
458
+
459
+ if use_sdp:
460
+ self.dp = StochasticDurationPredictor(hidden_channels, 192, 3, 0.5, 4, gin_channels=gin_channels)
461
+ else:
462
+ self.dp = DurationPredictor(hidden_channels, 256, 3, 0.5, gin_channels=gin_channels)
463
+
464
+ if n_speakers > 1:
465
+ self.emb_g = nn.Embedding(n_speakers, gin_channels)
466
+
467
+ def forward(self, x, x_lengths, y, y_lengths, sid=None):
468
+
469
+ x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths)
470
+ if self.n_speakers > 0:
471
+ g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
472
+ else:
473
+ g = None
474
+
475
+ z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
476
+ z_p = self.flow(z, y_mask, g=g)
477
+
478
+ with torch.no_grad():
479
+ # negative cross-entropy
480
+ s_p_sq_r = torch.exp(-2 * logs_p) # [b, d, t]
481
+ neg_cent1 = torch.sum(-0.5 * math.log(2 * math.pi) - logs_p, [1], keepdim=True) # [b, 1, t_s]
482
+ 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]
483
+ 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]
484
+ neg_cent4 = torch.sum(-0.5 * (m_p ** 2) * s_p_sq_r, [1], keepdim=True) # [b, 1, t_s]
485
+ neg_cent = neg_cent1 + neg_cent2 + neg_cent3 + neg_cent4
486
+
487
+ attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)
488
+ attn = monotonic_align.maximum_path(neg_cent, attn_mask.squeeze(1)).unsqueeze(1).detach()
489
+
490
+ w = attn.sum(2)
491
+ if self.use_sdp:
492
+ l_length = self.dp(x, x_mask, w, g=g)
493
+ l_length = l_length / torch.sum(x_mask)
494
+ else:
495
+ logw_ = torch.log(w + 1e-6) * x_mask
496
+ logw = self.dp(x, x_mask, g=g)
497
+ l_length = torch.sum((logw - logw_)**2, [1,2]) / torch.sum(x_mask) # for averaging
498
+
499
+ # expand prior
500
+ m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(1, 2)
501
+ logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(1, 2)
502
+
503
+ z_slice, ids_slice = commons.rand_slice_segments(z, y_lengths, self.segment_size)
504
+ o = self.dec(z_slice, g=g)
505
+ return o, l_length, attn, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q)
506
+
507
+ def infer(self, x, x_lengths, sid=None, noise_scale=1, length_scale=1, noise_scale_w=1., max_len=None, emotion_embedding=None):
508
+ x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths, emotion_embedding)
509
+ if self.n_speakers > 0:
510
+ g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
511
+ else:
512
+ g = None
513
+
514
+ if self.use_sdp:
515
+ logw = self.dp(x, x_mask, g=g, reverse=True, noise_scale=noise_scale_w)
516
+ else:
517
+ logw = self.dp(x, x_mask, g=g)
518
+ w = torch.exp(logw) * x_mask * length_scale
519
+ w_ceil = torch.ceil(w)
520
+ y_lengths = torch.clamp_min(torch.sum(w_ceil, [1, 2]), 1).long()
521
+ y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, None), 1).to(x_mask.dtype)
522
+ attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)
523
+ attn = commons.generate_path(w_ceil, attn_mask)
524
+
525
+ m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(1, 2) # [b, t', t], [b, t, d] -> [b, d, t']
526
+ logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(1, 2) # [b, t', t], [b, t, d] -> [b, d, t']
527
+
528
+ z_p = m_p + torch.randn_like(m_p) * torch.exp(logs_p) * noise_scale
529
+ z = self.flow(z_p, y_mask, g=g, reverse=True)
530
+ o = self.dec((z * y_mask)[:,:,:max_len], g=g)
531
+ return o, attn, y_mask, (z, z_p, m_p, logs_p)
532
+
533
+ def voice_conversion(self, y, y_lengths, sid_src, sid_tgt):
534
+ assert self.n_speakers > 0, "n_speakers have to be larger than 0."
535
+ g_src = self.emb_g(sid_src).unsqueeze(-1)
536
+ g_tgt = self.emb_g(sid_tgt).unsqueeze(-1)
537
+ z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g_src)
538
+ z_p = self.flow(z, y_mask, g=g_src)
539
+ z_hat = self.flow(z_p, y_mask, g=g_tgt, reverse=True)
540
+ o_hat = self.dec(z_hat * y_mask, g=g_tgt)
541
+ return o_hat, y_mask, (z, z_p, z_hat)
542
+
modules.py ADDED
@@ -0,0 +1,387 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ from torch import nn
4
+ from torch.nn import functional as F
5
+
6
+ from torch.nn import Conv1d
7
+ from torch.nn.utils import weight_norm, remove_weight_norm
8
+
9
+ import commons
10
+ from commons import init_weights, get_padding
11
+ from transforms import piecewise_rational_quadratic_transform
12
+
13
+
14
+ LRELU_SLOPE = 0.1
15
+
16
+
17
+ class LayerNorm(nn.Module):
18
+ def __init__(self, channels, eps=1e-5):
19
+ super().__init__()
20
+ self.channels = channels
21
+ self.eps = eps
22
+
23
+ self.gamma = nn.Parameter(torch.ones(channels))
24
+ self.beta = nn.Parameter(torch.zeros(channels))
25
+
26
+ def forward(self, x):
27
+ x = x.transpose(1, -1)
28
+ x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
29
+ return x.transpose(1, -1)
30
+
31
+
32
+ class ConvReluNorm(nn.Module):
33
+ def __init__(self, in_channels, hidden_channels, out_channels, kernel_size, n_layers, p_dropout):
34
+ super().__init__()
35
+ self.in_channels = in_channels
36
+ self.hidden_channels = hidden_channels
37
+ self.out_channels = out_channels
38
+ self.kernel_size = kernel_size
39
+ self.n_layers = n_layers
40
+ self.p_dropout = p_dropout
41
+ assert n_layers > 1, "Number of layers should be larger than 0."
42
+
43
+ self.conv_layers = nn.ModuleList()
44
+ self.norm_layers = nn.ModuleList()
45
+ self.conv_layers.append(nn.Conv1d(in_channels, hidden_channels, kernel_size, padding=kernel_size//2))
46
+ self.norm_layers.append(LayerNorm(hidden_channels))
47
+ self.relu_drop = nn.Sequential(
48
+ nn.ReLU(),
49
+ nn.Dropout(p_dropout))
50
+ for _ in range(n_layers-1):
51
+ self.conv_layers.append(nn.Conv1d(hidden_channels, hidden_channels, kernel_size, padding=kernel_size//2))
52
+ self.norm_layers.append(LayerNorm(hidden_channels))
53
+ self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
54
+ self.proj.weight.data.zero_()
55
+ self.proj.bias.data.zero_()
56
+
57
+ def forward(self, x, x_mask):
58
+ x_org = x
59
+ for i in range(self.n_layers):
60
+ x = self.conv_layers[i](x * x_mask)
61
+ x = self.norm_layers[i](x)
62
+ x = self.relu_drop(x)
63
+ x = x_org + self.proj(x)
64
+ return x * x_mask
65
+
66
+
67
+ class DDSConv(nn.Module):
68
+ """
69
+ Dialted and Depth-Separable Convolution
70
+ """
71
+ def __init__(self, channels, kernel_size, n_layers, p_dropout=0.):
72
+ super().__init__()
73
+ self.channels = channels
74
+ self.kernel_size = kernel_size
75
+ self.n_layers = n_layers
76
+ self.p_dropout = p_dropout
77
+
78
+ self.drop = nn.Dropout(p_dropout)
79
+ self.convs_sep = nn.ModuleList()
80
+ self.convs_1x1 = nn.ModuleList()
81
+ self.norms_1 = nn.ModuleList()
82
+ self.norms_2 = nn.ModuleList()
83
+ for i in range(n_layers):
84
+ dilation = kernel_size ** i
85
+ padding = (kernel_size * dilation - dilation) // 2
86
+ self.convs_sep.append(nn.Conv1d(channels, channels, kernel_size,
87
+ groups=channels, dilation=dilation, padding=padding
88
+ ))
89
+ self.convs_1x1.append(nn.Conv1d(channels, channels, 1))
90
+ self.norms_1.append(LayerNorm(channels))
91
+ self.norms_2.append(LayerNorm(channels))
92
+
93
+ def forward(self, x, x_mask, g=None):
94
+ if g is not None:
95
+ x = x + g
96
+ for i in range(self.n_layers):
97
+ y = self.convs_sep[i](x * x_mask)
98
+ y = self.norms_1[i](y)
99
+ y = F.gelu(y)
100
+ y = self.convs_1x1[i](y)
101
+ y = self.norms_2[i](y)
102
+ y = F.gelu(y)
103
+ y = self.drop(y)
104
+ x = x + y
105
+ return x * x_mask
106
+
107
+
108
+ class WN(torch.nn.Module):
109
+ def __init__(self, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=0, p_dropout=0):
110
+ super(WN, self).__init__()
111
+ assert(kernel_size % 2 == 1)
112
+ self.hidden_channels =hidden_channels
113
+ self.kernel_size = kernel_size,
114
+ self.dilation_rate = dilation_rate
115
+ self.n_layers = n_layers
116
+ self.gin_channels = gin_channels
117
+ self.p_dropout = p_dropout
118
+
119
+ self.in_layers = torch.nn.ModuleList()
120
+ self.res_skip_layers = torch.nn.ModuleList()
121
+ self.drop = nn.Dropout(p_dropout)
122
+
123
+ if gin_channels != 0:
124
+ cond_layer = torch.nn.Conv1d(gin_channels, 2*hidden_channels*n_layers, 1)
125
+ self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name='weight')
126
+
127
+ for i in range(n_layers):
128
+ dilation = dilation_rate ** i
129
+ padding = int((kernel_size * dilation - dilation) / 2)
130
+ in_layer = torch.nn.Conv1d(hidden_channels, 2*hidden_channels, kernel_size,
131
+ dilation=dilation, padding=padding)
132
+ in_layer = torch.nn.utils.weight_norm(in_layer, name='weight')
133
+ self.in_layers.append(in_layer)
134
+
135
+ # last one is not necessary
136
+ if i < n_layers - 1:
137
+ res_skip_channels = 2 * hidden_channels
138
+ else:
139
+ res_skip_channels = hidden_channels
140
+
141
+ res_skip_layer = torch.nn.Conv1d(hidden_channels, res_skip_channels, 1)
142
+ res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name='weight')
143
+ self.res_skip_layers.append(res_skip_layer)
144
+
145
+ def forward(self, x, x_mask, g=None, **kwargs):
146
+ output = torch.zeros_like(x)
147
+ n_channels_tensor = torch.IntTensor([self.hidden_channels])
148
+
149
+ if g is not None:
150
+ g = self.cond_layer(g)
151
+
152
+ for i in range(self.n_layers):
153
+ x_in = self.in_layers[i](x)
154
+ if g is not None:
155
+ cond_offset = i * 2 * self.hidden_channels
156
+ g_l = g[:,cond_offset:cond_offset+2*self.hidden_channels,:]
157
+ else:
158
+ g_l = torch.zeros_like(x_in)
159
+
160
+ acts = commons.fused_add_tanh_sigmoid_multiply(
161
+ x_in,
162
+ g_l,
163
+ n_channels_tensor)
164
+ acts = self.drop(acts)
165
+
166
+ res_skip_acts = self.res_skip_layers[i](acts)
167
+ if i < self.n_layers - 1:
168
+ res_acts = res_skip_acts[:,:self.hidden_channels,:]
169
+ x = (x + res_acts) * x_mask
170
+ output = output + res_skip_acts[:,self.hidden_channels:,:]
171
+ else:
172
+ output = output + res_skip_acts
173
+ return output * x_mask
174
+
175
+ def remove_weight_norm(self):
176
+ if self.gin_channels != 0:
177
+ torch.nn.utils.remove_weight_norm(self.cond_layer)
178
+ for l in self.in_layers:
179
+ torch.nn.utils.remove_weight_norm(l)
180
+ for l in self.res_skip_layers:
181
+ torch.nn.utils.remove_weight_norm(l)
182
+
183
+
184
+ class ResBlock1(torch.nn.Module):
185
+ def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):
186
+ super(ResBlock1, self).__init__()
187
+ self.convs1 = nn.ModuleList([
188
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
189
+ padding=get_padding(kernel_size, dilation[0]))),
190
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
191
+ padding=get_padding(kernel_size, dilation[1]))),
192
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[2],
193
+ padding=get_padding(kernel_size, dilation[2])))
194
+ ])
195
+ self.convs1.apply(init_weights)
196
+
197
+ self.convs2 = nn.ModuleList([
198
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
199
+ padding=get_padding(kernel_size, 1))),
200
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
201
+ padding=get_padding(kernel_size, 1))),
202
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
203
+ padding=get_padding(kernel_size, 1)))
204
+ ])
205
+ self.convs2.apply(init_weights)
206
+
207
+ def forward(self, x, x_mask=None):
208
+ for c1, c2 in zip(self.convs1, self.convs2):
209
+ xt = F.leaky_relu(x, LRELU_SLOPE)
210
+ if x_mask is not None:
211
+ xt = xt * x_mask
212
+ xt = c1(xt)
213
+ xt = F.leaky_relu(xt, LRELU_SLOPE)
214
+ if x_mask is not None:
215
+ xt = xt * x_mask
216
+ xt = c2(xt)
217
+ x = xt + x
218
+ if x_mask is not None:
219
+ x = x * x_mask
220
+ return x
221
+
222
+ def remove_weight_norm(self):
223
+ for l in self.convs1:
224
+ remove_weight_norm(l)
225
+ for l in self.convs2:
226
+ remove_weight_norm(l)
227
+
228
+
229
+ class ResBlock2(torch.nn.Module):
230
+ def __init__(self, channels, kernel_size=3, dilation=(1, 3)):
231
+ super(ResBlock2, self).__init__()
232
+ self.convs = nn.ModuleList([
233
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
234
+ padding=get_padding(kernel_size, dilation[0]))),
235
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
236
+ padding=get_padding(kernel_size, dilation[1])))
237
+ ])
238
+ self.convs.apply(init_weights)
239
+
240
+ def forward(self, x, x_mask=None):
241
+ for c in self.convs:
242
+ xt = F.leaky_relu(x, LRELU_SLOPE)
243
+ if x_mask is not None:
244
+ xt = xt * x_mask
245
+ xt = c(xt)
246
+ x = xt + x
247
+ if x_mask is not None:
248
+ x = x * x_mask
249
+ return x
250
+
251
+ def remove_weight_norm(self):
252
+ for l in self.convs:
253
+ remove_weight_norm(l)
254
+
255
+
256
+ class Log(nn.Module):
257
+ def forward(self, x, x_mask, reverse=False, **kwargs):
258
+ if not reverse:
259
+ y = torch.log(torch.clamp_min(x, 1e-5)) * x_mask
260
+ logdet = torch.sum(-y, [1, 2])
261
+ return y, logdet
262
+ else:
263
+ x = torch.exp(x) * x_mask
264
+ return x
265
+
266
+
267
+ class Flip(nn.Module):
268
+ def forward(self, x, *args, reverse=False, **kwargs):
269
+ x = torch.flip(x, [1])
270
+ if not reverse:
271
+ logdet = torch.zeros(x.size(0)).to(dtype=x.dtype, device=x.device)
272
+ return x, logdet
273
+ else:
274
+ return x
275
+
276
+
277
+ class ElementwiseAffine(nn.Module):
278
+ def __init__(self, channels):
279
+ super().__init__()
280
+ self.channels = channels
281
+ self.m = nn.Parameter(torch.zeros(channels,1))
282
+ self.logs = nn.Parameter(torch.zeros(channels,1))
283
+
284
+ def forward(self, x, x_mask, reverse=False, **kwargs):
285
+ if not reverse:
286
+ y = self.m + torch.exp(self.logs) * x
287
+ y = y * x_mask
288
+ logdet = torch.sum(self.logs * x_mask, [1,2])
289
+ return y, logdet
290
+ else:
291
+ x = (x - self.m) * torch.exp(-self.logs) * x_mask
292
+ return x
293
+
294
+
295
+ class ResidualCouplingLayer(nn.Module):
296
+ def __init__(self,
297
+ channels,
298
+ hidden_channels,
299
+ kernel_size,
300
+ dilation_rate,
301
+ n_layers,
302
+ p_dropout=0,
303
+ gin_channels=0,
304
+ mean_only=False):
305
+ assert channels % 2 == 0, "channels should be divisible by 2"
306
+ super().__init__()
307
+ self.channels = channels
308
+ self.hidden_channels = hidden_channels
309
+ self.kernel_size = kernel_size
310
+ self.dilation_rate = dilation_rate
311
+ self.n_layers = n_layers
312
+ self.half_channels = channels // 2
313
+ self.mean_only = mean_only
314
+
315
+ self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
316
+ self.enc = WN(hidden_channels, kernel_size, dilation_rate, n_layers, p_dropout=p_dropout, gin_channels=gin_channels)
317
+ self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
318
+ self.post.weight.data.zero_()
319
+ self.post.bias.data.zero_()
320
+
321
+ def forward(self, x, x_mask, g=None, reverse=False):
322
+ x0, x1 = torch.split(x, [self.half_channels]*2, 1)
323
+ h = self.pre(x0) * x_mask
324
+ h = self.enc(h, x_mask, g=g)
325
+ stats = self.post(h) * x_mask
326
+ if not self.mean_only:
327
+ m, logs = torch.split(stats, [self.half_channels]*2, 1)
328
+ else:
329
+ m = stats
330
+ logs = torch.zeros_like(m)
331
+
332
+ if not reverse:
333
+ x1 = m + x1 * torch.exp(logs) * x_mask
334
+ x = torch.cat([x0, x1], 1)
335
+ logdet = torch.sum(logs, [1,2])
336
+ return x, logdet
337
+ else:
338
+ x1 = (x1 - m) * torch.exp(-logs) * x_mask
339
+ x = torch.cat([x0, x1], 1)
340
+ return x
341
+
342
+
343
+ class ConvFlow(nn.Module):
344
+ def __init__(self, in_channels, filter_channels, kernel_size, n_layers, num_bins=10, tail_bound=5.0):
345
+ super().__init__()
346
+ self.in_channels = in_channels
347
+ self.filter_channels = filter_channels
348
+ self.kernel_size = kernel_size
349
+ self.n_layers = n_layers
350
+ self.num_bins = num_bins
351
+ self.tail_bound = tail_bound
352
+ self.half_channels = in_channels // 2
353
+
354
+ self.pre = nn.Conv1d(self.half_channels, filter_channels, 1)
355
+ self.convs = DDSConv(filter_channels, kernel_size, n_layers, p_dropout=0.)
356
+ self.proj = nn.Conv1d(filter_channels, self.half_channels * (num_bins * 3 - 1), 1)
357
+ self.proj.weight.data.zero_()
358
+ self.proj.bias.data.zero_()
359
+
360
+ def forward(self, x, x_mask, g=None, reverse=False):
361
+ x0, x1 = torch.split(x, [self.half_channels]*2, 1)
362
+ h = self.pre(x0)
363
+ h = self.convs(h, x_mask, g=g)
364
+ h = self.proj(h) * x_mask
365
+
366
+ b, c, t = x0.shape
367
+ h = h.reshape(b, c, -1, t).permute(0, 1, 3, 2) # [b, cx?, t] -> [b, c, t, ?]
368
+
369
+ unnormalized_widths = h[..., :self.num_bins] / math.sqrt(self.filter_channels)
370
+ unnormalized_heights = h[..., self.num_bins:2*self.num_bins] / math.sqrt(self.filter_channels)
371
+ unnormalized_derivatives = h[..., 2 * self.num_bins:]
372
+
373
+ x1, logabsdet = piecewise_rational_quadratic_transform(x1,
374
+ unnormalized_widths,
375
+ unnormalized_heights,
376
+ unnormalized_derivatives,
377
+ inverse=reverse,
378
+ tails='linear',
379
+ tail_bound=self.tail_bound
380
+ )
381
+
382
+ x = torch.cat([x0, x1], 1) * x_mask
383
+ logdet = torch.sum(logabsdet * x_mask, [1,2])
384
+ if not reverse:
385
+ return x, logdet
386
+ else:
387
+ return x
monotonic_align/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ from .monotonic_align.core import maximum_path_c
4
+
5
+
6
+ def maximum_path(neg_cent, mask):
7
+ """ Cython optimized version.
8
+ neg_cent: [b, t_t, t_s]
9
+ mask: [b, t_t, t_s]
10
+ """
11
+ device = neg_cent.device
12
+ dtype = neg_cent.dtype
13
+ neg_cent = neg_cent.data.cpu().numpy().astype(np.float32)
14
+ path = np.zeros(neg_cent.shape, dtype=np.int32)
15
+
16
+ t_t_max = mask.sum(1)[:, 0].data.cpu().numpy().astype(np.int32)
17
+ t_s_max = mask.sum(2)[:, 0].data.cpu().numpy().astype(np.int32)
18
+ maximum_path_c(path, neg_cent, t_t_max, t_s_max)
19
+ return torch.from_numpy(path).to(device=device, dtype=dtype)
monotonic_align/__pycache__/__init__.cpython-37.pyc ADDED
Binary file (765 Bytes). View file
 
monotonic_align/build/lib.win-amd64-cpython-37/monotonic_align/core.cp37-win_amd64.pyd ADDED
Binary file (120 kB). View file
 
monotonic_align/build/temp.win-amd64-cpython-37/Release/core.cp37-win_amd64.exp ADDED
Binary file (697 Bytes). View file
 
monotonic_align/build/temp.win-amd64-cpython-37/Release/core.cp37-win_amd64.lib ADDED
Binary file (1.94 kB). View file
 
monotonic_align/build/temp.win-amd64-cpython-37/Release/core.obj ADDED
Binary file (848 kB). View file
 
monotonic_align/core.c ADDED
The diff for this file is too large to render. See raw diff
 
monotonic_align/core.pyx ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cimport cython
2
+ from cython.parallel import prange
3
+
4
+
5
+ @cython.boundscheck(False)
6
+ @cython.wraparound(False)
7
+ cdef void maximum_path_each(int[:,::1] path, float[:,::1] value, int t_y, int t_x, float max_neg_val=-1e9) nogil:
8
+ cdef int x
9
+ cdef int y
10
+ cdef float v_prev
11
+ cdef float v_cur
12
+ cdef float tmp
13
+ cdef int index = t_x - 1
14
+
15
+ for y in range(t_y):
16
+ for x in range(max(0, t_x + y - t_y), min(t_x, y + 1)):
17
+ if x == y:
18
+ v_cur = max_neg_val
19
+ else:
20
+ v_cur = value[y-1, x]
21
+ if x == 0:
22
+ if y == 0:
23
+ v_prev = 0.
24
+ else:
25
+ v_prev = max_neg_val
26
+ else:
27
+ v_prev = value[y-1, x-1]
28
+ value[y, x] += max(v_prev, v_cur)
29
+
30
+ for y in range(t_y - 1, -1, -1):
31
+ path[y, index] = 1
32
+ if index != 0 and (index == y or value[y-1, index] < value[y-1, index-1]):
33
+ index = index - 1
34
+
35
+
36
+ @cython.boundscheck(False)
37
+ @cython.wraparound(False)
38
+ cpdef void maximum_path_c(int[:,:,::1] paths, float[:,:,::1] values, int[::1] t_ys, int[::1] t_xs) nogil:
39
+ cdef int b = paths.shape[0]
40
+ cdef int i
41
+ for i in prange(b, nogil=True):
42
+ maximum_path_each(paths[i], values[i], t_ys[i], t_xs[i])
monotonic_align/monotonic_align/core.cp37-win_amd64.pyd ADDED
Binary file (120 kB). View file
 
monotonic_align/setup.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from distutils.core import setup
2
+ from Cython.Build import cythonize
3
+ import numpy
4
+
5
+ setup(
6
+ name = 'monotonic_align',
7
+ ext_modules = cythonize("core.pyx"),
8
+ include_dirs=[numpy.get_include()]
9
+ )
pretrained_models/D_trilingual.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:920fb34bf3dc466e761996e787952a7bd53d4f6699561e9141bcbcf4f3f34092
3
+ size 187024867
pretrained_models/G_jp.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4a53f4eb6bf8226b3fb4a3b31436235f697692f5566039ce3491b80af9a9567a
3
+ size 158962765
pretrained_models/G_trilingual.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:651381372bd0936fa90cdcfd75c8c4c231edd341a180466fc65dd3f75c5e4d70
3
+ size 159918157
requirements.txt ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ numba
2
+ librosa
3
+ matplotlib
4
+ numpy
5
+ phonemizer
6
+ scipy
7
+ tensorboard
8
+ torch
9
+ torchvision
10
+ torchaudio
11
+ unidecode
12
+ pyopenjtalk>=0.3.0
13
+ jamo
14
+ pypinyin
15
+ ko_pron
16
+ jieba
17
+ cn2an
18
+ protobuf
19
+ inflect
20
+ eng_to_ipa
21
+ ko_pron
22
+ indic_transliteration
23
+ num_thai
24
+ opencc
25
+ onnx
26
+ onnxruntime
27
+ psutil
28
+ gradio
text/LICENSE ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (c) 2017 Keith Ito
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in
11
+ all copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19
+ THE SOFTWARE.
text/__init__.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ from https://github.com/keithito/tacotron """
2
+ from text import cleaners
3
+
4
+
5
+ def text_to_sequence(text, symbols, cleaner_names):
6
+ '''Converts a string of text to a sequence of IDs corresponding to the symbols in the text.
7
+ Args:
8
+ text: string to convert to a sequence
9
+ cleaner_names: names of the cleaner functions to run the text through
10
+ Returns:
11
+ List of integers corresponding to the symbols in the text
12
+ '''
13
+ _symbol_to_id = {s: i for i, s in enumerate(symbols)}
14
+
15
+ sequence = []
16
+
17
+ clean_text = _clean_text(text, cleaner_names)
18
+ for symbol in clean_text:
19
+ if symbol not in _symbol_to_id.keys():
20
+ continue
21
+ symbol_id = _symbol_to_id[symbol]
22
+ sequence += [symbol_id]
23
+ return sequence
24
+
25
+
26
+ def _clean_text(text, cleaner_names):
27
+ for name in cleaner_names:
28
+ cleaner = getattr(cleaners, name)
29
+ if not cleaner:
30
+ raise Exception('Unknown cleaner: %s' % name)
31
+ text = cleaner(text)
32
+ return text
text/__pycache__/__init__.cpython-37.pyc ADDED
Binary file (1.19 kB). View file
 
text/__pycache__/cleaners.cpython-37.pyc ADDED
Binary file (7.74 kB). View file
 
text/__pycache__/english.cpython-37.pyc ADDED
Binary file (4.93 kB). View file
 
text/__pycache__/japanese.cpython-37.pyc ADDED
Binary file (4.61 kB). View file
 
text/__pycache__/korean.cpython-37.pyc ADDED
Binary file (5.75 kB). View file