kiramayatu commited on
Commit
ee67709
1 Parent(s): b6cadb1

Upload 7 files

Browse files
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