MRiwu/Collection
1
1import copy2import math3import numpy as np4import scipy5import torch6from torch import nn7from torch.nn import functional as F8 9from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d10from torch.nn.utils import weight_norm, remove_weight_norm11 12import commons13from commons import init_weights, get_padding14from transforms import piecewise_rational_quadratic_transform15 16 17LRELU_SLOPE = 0.118 19 20class LayerNorm(nn.Module):21 def __init__(self, channels, eps=1e-5):22 super().__init__()23 self.channels = channels24 self.eps = eps25 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 35class 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_channels39 self.hidden_channels = hidden_channels40 self.out_channels = out_channels41 self.kernel_size = kernel_size42 self.n_layers = n_layers43 self.p_dropout = p_dropout44 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 = x62 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_mask68 69 70class DDSConv(nn.Module):71 """72 Dilated and Depth-Separable Convolution73 """74 def __init__(self, channels, kernel_size, n_layers, p_dropout=0.):75 super().__init__()76 self.channels = channels77 self.kernel_size = kernel_size78 self.n_layers = n_layers79 self.p_dropout = p_dropout80 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 ** i88 padding = (kernel_size * dilation - dilation) // 289 self.convs_sep.append(nn.Conv1d(channels, channels, kernel_size, 90 groups=channels, dilation=dilation, padding=padding91 ))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 + g99 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 + y108 return x * x_mask109 110 111class 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_channels116 self.kernel_size = kernel_size,117 self.dilation_rate = dilation_rate118 self.n_layers = n_layers119 self.gin_channels = gin_channels120 self.p_dropout = p_dropout121 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 ** i132 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 necessary139 if i < n_layers - 1:140 res_skip_channels = 2 * hidden_channels141 else:142 res_skip_channels = hidden_channels143 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_channels159 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_mask173 output = output + res_skip_acts[:,self.hidden_channels:,:]174 else:175 output = output + res_skip_acts176 return output * x_mask177 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 187class 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_mask215 xt = c1(xt)216 xt = F.leaky_relu(xt, LRELU_SLOPE)217 if x_mask is not None:218 xt = xt * x_mask219 xt = c2(xt)220 x = xt + x221 if x_mask is not None:222 x = x * x_mask223 return x224 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 232class 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_mask248 xt = c(xt)249 x = xt + x250 if x_mask is not None:251 x = x * x_mask252 return x253 254 def remove_weight_norm(self):255 for l in self.convs:256 remove_weight_norm(l)257 258 259class 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_mask263 logdet = torch.sum(-y, [1, 2])264 return y, logdet265 else:266 x = torch.exp(x) * x_mask267 return x268 269 270class 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, logdet276 else:277 return x278 279 280class ElementwiseAffine(nn.Module):281 def __init__(self, channels):282 super().__init__()283 self.channels = channels284 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) * x290 y = y * x_mask291 logdet = torch.sum(self.logs * x_mask, [1,2])292 return y, logdet293 else:294 x = (x - self.m) * torch.exp(-self.logs) * x_mask295 return x296 297 298class 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 = channels311 self.hidden_channels = hidden_channels312 self.kernel_size = kernel_size313 self.dilation_rate = dilation_rate314 self.n_layers = n_layers315 self.half_channels = channels // 2316 self.mean_only = mean_only317 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_mask327 h = self.enc(h, x_mask, g=g)328 stats = self.post(h) * x_mask329 if not self.mean_only:330 m, logs = torch.split(stats, [self.half_channels]*2, 1)331 else:332 m = stats333 logs = torch.zeros_like(m)334 335 if not reverse:336 x1 = m + x1 * torch.exp(logs) * x_mask337 x = torch.cat([x0, x1], 1)338 logdet = torch.sum(logs, [1,2])339 return x, logdet340 else:341 x1 = (x1 - m) * torch.exp(-logs) * x_mask342 x = torch.cat([x0, x1], 1)343 return x344 345 346class 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_channels350 self.filter_channels = filter_channels351 self.kernel_size = kernel_size352 self.n_layers = n_layers353 self.num_bins = num_bins354 self.tail_bound = tail_bound355 self.half_channels = in_channels // 2356 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_mask368 369 b, c, t = x0.shape370 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_bound383 )384 385 x = torch.cat([x0, x1], 1) * x_mask386 logdet = torch.sum(logabsdet * x_mask, [1,2])387 if not reverse:388 return x, logdet389 else:390 return x391 