lakiH/kai
0
1import math2import numpy as np3import torch4from torch import nn5from torch.nn import functional as F6 7from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d8from torch.nn.utils import weight_norm, remove_weight_norm9 10import commons11from commons import init_weights, get_padding12from transforms import piecewise_rational_quadratic_transform13 14 15LRELU_SLOPE = 0.116 17 18class LayerNorm(nn.Module):19 def __init__(self, channels, eps=1e-5):20 super().__init__()21 self.channels = channels22 self.eps = eps23 24 self.gamma = nn.Parameter(torch.ones(channels))25 self.beta = nn.Parameter(torch.zeros(channels))26 27 def forward(self, x):28 x = x.transpose(1, -1)29 x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)30 return x.transpose(1, -1)31 32 33class ConvReluNorm(nn.Module):34 def __init__(self, in_channels, hidden_channels, out_channels, kernel_size, n_layers, p_dropout):35 super().__init__()36 self.in_channels = in_channels37 self.hidden_channels = hidden_channels38 self.out_channels = out_channels39 self.kernel_size = kernel_size40 self.n_layers = n_layers41 self.p_dropout = p_dropout42 assert n_layers > 1, "Number of layers should be larger than 0."43 44 self.conv_layers = nn.ModuleList()45 self.norm_layers = nn.ModuleList()46 self.conv_layers.append(nn.Conv1d(in_channels, hidden_channels, kernel_size, padding=kernel_size//2))47 self.norm_layers.append(LayerNorm(hidden_channels))48 self.relu_drop = nn.Sequential(49 nn.ReLU(),50 nn.Dropout(p_dropout))51 for _ in range(n_layers-1):52 self.conv_layers.append(nn.Conv1d(hidden_channels, hidden_channels, kernel_size, padding=kernel_size//2))53 self.norm_layers.append(LayerNorm(hidden_channels))54 self.proj = nn.Conv1d(hidden_channels, out_channels, 1)55 self.proj.weight.data.zero_()56 self.proj.bias.data.zero_()57 58 def forward(self, x, x_mask):59 x_org = x60 for i in range(self.n_layers):61 x = self.conv_layers[i](x * x_mask)62 x = self.norm_layers[i](x)63 x = self.relu_drop(x)64 x = x_org + self.proj(x)65 return x * x_mask66 67 68class DDSConv(nn.Module):69 """70 Dialted and Depth-Separable Convolution71 """72 def __init__(self, channels, kernel_size, n_layers, p_dropout=0.):73 super().__init__()74 self.channels = channels75 self.kernel_size = kernel_size76 self.n_layers = n_layers77 self.p_dropout = p_dropout78 79 self.drop = nn.Dropout(p_dropout)80 self.convs_sep = nn.ModuleList()81 self.convs_1x1 = nn.ModuleList()82 self.norms_1 = nn.ModuleList()83 self.norms_2 = nn.ModuleList()84 for i in range(n_layers):85 dilation = kernel_size ** i86 padding = (kernel_size * dilation - dilation) // 287 self.convs_sep.append(nn.Conv1d(channels, channels, kernel_size, 88 groups=channels, dilation=dilation, padding=padding89 ))90 self.convs_1x1.append(nn.Conv1d(channels, channels, 1))91 self.norms_1.append(LayerNorm(channels))92 self.norms_2.append(LayerNorm(channels))93 94 def forward(self, x, x_mask, g=None):95 if g is not None:96 x = x + g97 for i in range(self.n_layers):98 y = self.convs_sep[i](x * x_mask)99 y = self.norms_1[i](y)100 y = F.gelu(y)101 y = self.convs_1x1[i](y)102 y = self.norms_2[i](y)103 y = F.gelu(y)104 y = self.drop(y)105 x = x + y106 return x * x_mask107 108 109class WN(torch.nn.Module):110 def __init__(self, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=0, p_dropout=0):111 super(WN, self).__init__()112 assert(kernel_size % 2 == 1)113 self.hidden_channels =hidden_channels114 self.kernel_size = kernel_size,115 self.dilation_rate = dilation_rate116 self.n_layers = n_layers117 self.gin_channels = gin_channels118 self.p_dropout = p_dropout119 120 self.in_layers = torch.nn.ModuleList()121 self.res_skip_layers = torch.nn.ModuleList()122 self.drop = nn.Dropout(p_dropout)123 124 if gin_channels != 0:125 cond_layer = torch.nn.Conv1d(gin_channels, 2*hidden_channels*n_layers, 1)126 self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name='weight')127 128 for i in range(n_layers):129 dilation = dilation_rate ** i130 padding = int((kernel_size * dilation - dilation) / 2)131 in_layer = torch.nn.Conv1d(hidden_channels, 2*hidden_channels, kernel_size,132 dilation=dilation, padding=padding)133 in_layer = torch.nn.utils.weight_norm(in_layer, name='weight')134 self.in_layers.append(in_layer)135 136 # last one is not necessary137 if i < n_layers - 1:138 res_skip_channels = 2 * hidden_channels139 else:140 res_skip_channels = hidden_channels141 142 res_skip_layer = torch.nn.Conv1d(hidden_channels, res_skip_channels, 1)143 res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name='weight')144 self.res_skip_layers.append(res_skip_layer)145 146 def forward(self, x, x_mask, g=None, **kwargs):147 output = torch.zeros_like(x)148 n_channels_tensor = torch.IntTensor([self.hidden_channels])149 150 if g is not None:151 g = self.cond_layer(g)152 153 for i in range(self.n_layers):154 x_in = self.in_layers[i](x)155 if g is not None:156 cond_offset = i * 2 * self.hidden_channels157 g_l = g[:,cond_offset:cond_offset+2*self.hidden_channels,:]158 else:159 g_l = torch.zeros_like(x_in)160 161 acts = commons.fused_add_tanh_sigmoid_multiply(162 x_in,163 g_l,164 n_channels_tensor)165 acts = self.drop(acts)166 167 res_skip_acts = self.res_skip_layers[i](acts)168 if i < self.n_layers - 1:169 res_acts = res_skip_acts[:,:self.hidden_channels,:]170 x = (x + res_acts) * x_mask171 output = output + res_skip_acts[:,self.hidden_channels:,:]172 else:173 output = output + res_skip_acts174 return output * x_mask175 176 def remove_weight_norm(self):177 if self.gin_channels != 0:178 torch.nn.utils.remove_weight_norm(self.cond_layer)179 for l in self.in_layers:180 torch.nn.utils.remove_weight_norm(l)181 for l in self.res_skip_layers:182 torch.nn.utils.remove_weight_norm(l)183 184 185class ResBlock1(torch.nn.Module):186 def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):187 super(ResBlock1, self).__init__()188 self.convs1 = nn.ModuleList([189 weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],190 padding=get_padding(kernel_size, dilation[0]))),191 weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],192 padding=get_padding(kernel_size, dilation[1]))),193 weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[2],194 padding=get_padding(kernel_size, dilation[2])))195 ])196 self.convs1.apply(init_weights)197 198 self.convs2 = nn.ModuleList([199 weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,200 padding=get_padding(kernel_size, 1))),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 ])206 self.convs2.apply(init_weights)207 208 def forward(self, x, x_mask=None):209 for c1, c2 in zip(self.convs1, self.convs2):210 xt = F.leaky_relu(x, LRELU_SLOPE)211 if x_mask is not None:212 xt = xt * x_mask213 xt = c1(xt)214 xt = F.leaky_relu(xt, LRELU_SLOPE)215 if x_mask is not None:216 xt = xt * x_mask217 xt = c2(xt)218 x = xt + x219 if x_mask is not None:220 x = x * x_mask221 return x222 223 def remove_weight_norm(self):224 for l in self.convs1:225 remove_weight_norm(l)226 for l in self.convs2:227 remove_weight_norm(l)228 229 230class ResBlock2(torch.nn.Module):231 def __init__(self, channels, kernel_size=3, dilation=(1, 3)):232 super(ResBlock2, self).__init__()233 self.convs = nn.ModuleList([234 weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],235 padding=get_padding(kernel_size, dilation[0]))),236 weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],237 padding=get_padding(kernel_size, dilation[1])))238 ])239 self.convs.apply(init_weights)240 241 def forward(self, x, x_mask=None):242 for c in self.convs:243 xt = F.leaky_relu(x, LRELU_SLOPE)244 if x_mask is not None:245 xt = xt * x_mask246 xt = c(xt)247 x = xt + x248 if x_mask is not None:249 x = x * x_mask250 return x251 252 def remove_weight_norm(self):253 for l in self.convs:254 remove_weight_norm(l)255 256 257class Log(nn.Module):258 def forward(self, x, x_mask, reverse=False, **kwargs):259 if not reverse:260 y = torch.log(torch.clamp_min(x, 1e-5)) * x_mask261 logdet = torch.sum(-y, [1, 2])262 return y, logdet263 else:264 x = torch.exp(x) * x_mask265 return x266 267 268class Flip(nn.Module):269 def forward(self, x, *args, reverse=False, **kwargs):270 x = torch.flip(x, [1])271 if not reverse:272 logdet = torch.zeros(x.size(0)).to(dtype=x.dtype, device=x.device)273 return x, logdet274 else:275 return x276 277 278class ElementwiseAffine(nn.Module):279 def __init__(self, channels):280 super().__init__()281 self.channels = channels282 self.m = nn.Parameter(torch.zeros(channels,1))283 self.logs = nn.Parameter(torch.zeros(channels,1))284 285 def forward(self, x, x_mask, reverse=False, **kwargs):286 if not reverse:287 y = self.m + torch.exp(self.logs) * x288 y = y * x_mask289 logdet = torch.sum(self.logs * x_mask, [1,2])290 return y, logdet291 else:292 x = (x - self.m) * torch.exp(-self.logs) * x_mask293 return x294 295 296class ResidualCouplingLayer(nn.Module):297 def __init__(self,298 channels,299 hidden_channels,300 kernel_size,301 dilation_rate,302 n_layers,303 p_dropout=0,304 gin_channels=0,305 mean_only=False):306 assert channels % 2 == 0, "channels should be divisible by 2"307 super().__init__()308 self.channels = channels309 self.hidden_channels = hidden_channels310 self.kernel_size = kernel_size311 self.dilation_rate = dilation_rate312 self.n_layers = n_layers313 self.half_channels = channels // 2314 self.mean_only = mean_only315 316 self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)317 self.enc = WN(hidden_channels, kernel_size, dilation_rate, n_layers, p_dropout=p_dropout, gin_channels=gin_channels)318 self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)319 self.post.weight.data.zero_()320 self.post.bias.data.zero_()321 322 def forward(self, x, x_mask, g=None, reverse=False):323 x0, x1 = torch.split(x, [self.half_channels]*2, 1)324 h = self.pre(x0) * x_mask325 h = self.enc(h, x_mask, g=g)326 stats = self.post(h) * x_mask327 if not self.mean_only:328 m, logs = torch.split(stats, [self.half_channels]*2, 1)329 else:330 m = stats331 logs = torch.zeros_like(m)332 333 if not reverse:334 x1 = m + x1 * torch.exp(logs) * x_mask335 x = torch.cat([x0, x1], 1)336 logdet = torch.sum(logs, [1,2])337 return x, logdet338 else:339 x1 = (x1 - m) * torch.exp(-logs) * x_mask340 x = torch.cat([x0, x1], 1)341 return x342 343 344class ConvFlow(nn.Module):345 def __init__(self, in_channels, filter_channels, kernel_size, n_layers, num_bins=10, tail_bound=5.0):346 super().__init__()347 self.in_channels = in_channels348 self.filter_channels = filter_channels349 self.kernel_size = kernel_size350 self.n_layers = n_layers351 self.num_bins = num_bins352 self.tail_bound = tail_bound353 self.half_channels = in_channels // 2354 355 self.pre = nn.Conv1d(self.half_channels, filter_channels, 1)356 self.convs = DDSConv(filter_channels, kernel_size, n_layers, p_dropout=0.)357 self.proj = nn.Conv1d(filter_channels, self.half_channels * (num_bins * 3 - 1), 1)358 self.proj.weight.data.zero_()359 self.proj.bias.data.zero_()360 361 def forward(self, x, x_mask, g=None, reverse=False):362 x0, x1 = torch.split(x, [self.half_channels]*2, 1)363 h = self.pre(x0)364 h = self.convs(h, x_mask, g=g)365 h = self.proj(h) * x_mask366 367 b, c, t = x0.shape368 h = h.reshape(b, c, -1, t).permute(0, 1, 3, 2) # [b, cx?, t] -> [b, c, t, ?]369 370 unnormalized_widths = h[..., :self.num_bins] / math.sqrt(self.filter_channels)371 unnormalized_heights = h[..., self.num_bins:2*self.num_bins] / math.sqrt(self.filter_channels)372 unnormalized_derivatives = h[..., 2 * self.num_bins:]373 374 x1, logabsdet = piecewise_rational_quadratic_transform(x1,375 unnormalized_widths,376 unnormalized_heights,377 unnormalized_derivatives,378 inverse=reverse,379 tails='linear',380 tail_bound=self.tail_bound381 )382 383 x = torch.cat([x0, x1], 1) * x_mask384 logdet = torch.sum(logabsdet * x_mask, [1,2])385 if not reverse:386 return x, logdet387 else:388 return x389 