kevinwang676/FreeVC-OpenAI-TTS
0
1import math2import numpy as np3import torch4from torch import nn5from torch.nn import functional as F6 7 8def init_weights(m, mean=0.0, std=0.01):9 classname = m.__class__.__name__10 if classname.find("Conv") != -1:11 m.weight.data.normal_(mean, std)12 13 14def get_padding(kernel_size, dilation=1):15 return int((kernel_size*dilation - dilation)/2)16 17 18def convert_pad_shape(pad_shape):19 l = pad_shape[::-1]20 pad_shape = [item for sublist in l for item in sublist]21 return pad_shape22 23 24def intersperse(lst, item):25 result = [item] * (len(lst) * 2 + 1)26 result[1::2] = lst27 return result28 29 30def kl_divergence(m_p, logs_p, m_q, logs_q):31 """KL(P||Q)"""32 kl = (logs_q - logs_p) - 0.533 kl += 0.5 * (torch.exp(2. * logs_p) + ((m_p - m_q)**2)) * torch.exp(-2. * logs_q)34 return kl35 36 37def rand_gumbel(shape):38 """Sample from the Gumbel distribution, protect from overflows."""39 uniform_samples = torch.rand(shape) * 0.99998 + 0.0000140 return -torch.log(-torch.log(uniform_samples))41 42 43def rand_gumbel_like(x):44 g = rand_gumbel(x.size()).to(dtype=x.dtype, device=x.device)45 return g46 47 48def slice_segments(x, ids_str, segment_size=4):49 ret = torch.zeros_like(x[:, :, :segment_size])50 for i in range(x.size(0)):51 idx_str = ids_str[i]52 idx_end = idx_str + segment_size53 ret[i] = x[i, :, idx_str:idx_end]54 return ret55 56 57def rand_slice_segments(x, x_lengths=None, segment_size=4):58 b, d, t = x.size()59 if x_lengths is None:60 x_lengths = t61 ids_str_max = x_lengths - segment_size + 162 ids_str = (torch.rand([b]).to(device=x.device) * ids_str_max).to(dtype=torch.long)63 ret = slice_segments(x, ids_str, segment_size)64 return ret, ids_str65 66 67def rand_spec_segments(x, x_lengths=None, segment_size=4):68 b, d, t = x.size()69 if x_lengths is None:70 x_lengths = t71 ids_str_max = x_lengths - segment_size72 ids_str = (torch.rand([b]).to(device=x.device) * ids_str_max).to(dtype=torch.long)73 ret = slice_segments(x, ids_str, segment_size)74 return ret, ids_str75 76 77def get_timing_signal_1d(78 length, channels, min_timescale=1.0, max_timescale=1.0e4):79 position = torch.arange(length, dtype=torch.float)80 num_timescales = channels // 281 log_timescale_increment = (82 math.log(float(max_timescale) / float(min_timescale)) /83 (num_timescales - 1))84 inv_timescales = min_timescale * torch.exp(85 torch.arange(num_timescales, dtype=torch.float) * -log_timescale_increment)86 scaled_time = position.unsqueeze(0) * inv_timescales.unsqueeze(1)87 signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], 0)88 signal = F.pad(signal, [0, 0, 0, channels % 2])89 signal = signal.view(1, channels, length)90 return signal91 92 93def add_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4):94 b, channels, length = x.size()95 signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)96 return x + signal.to(dtype=x.dtype, device=x.device)97 98 99def cat_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4, axis=1):100 b, channels, length = x.size()101 signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)102 return torch.cat([x, signal.to(dtype=x.dtype, device=x.device)], axis)103 104 105def subsequent_mask(length):106 mask = torch.tril(torch.ones(length, length)).unsqueeze(0).unsqueeze(0)107 return mask108 109 110@torch.jit.script111def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):112 n_channels_int = n_channels[0]113 in_act = input_a + input_b114 t_act = torch.tanh(in_act[:, :n_channels_int, :])115 s_act = torch.sigmoid(in_act[:, n_channels_int:, :])116 acts = t_act * s_act117 return acts118 119 120def convert_pad_shape(pad_shape):121 l = pad_shape[::-1]122 pad_shape = [item for sublist in l for item in sublist]123 return pad_shape124 125 126def shift_1d(x):127 x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [1, 0]]))[:, :, :-1]128 return x129 130 131def sequence_mask(length, max_length=None):132 if max_length is None:133 max_length = length.max()134 x = torch.arange(max_length, dtype=length.dtype, device=length.device)135 return x.unsqueeze(0) < length.unsqueeze(1)136 137 138def generate_path(duration, mask):139 """140 duration: [b, 1, t_x]141 mask: [b, 1, t_y, t_x]142 """143 device = duration.device144 145 b, _, t_y, t_x = mask.shape146 cum_duration = torch.cumsum(duration, -1)147 148 cum_duration_flat = cum_duration.view(b * t_x)149 path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype)150 path = path.view(b, t_x, t_y)151 path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1]152 path = path.unsqueeze(1).transpose(2,3) * mask153 return path154 155 156def clip_grad_value_(parameters, clip_value, norm_type=2):157 if isinstance(parameters, torch.Tensor):158 parameters = [parameters]159 parameters = list(filter(lambda p: p.grad is not None, parameters))160 norm_type = float(norm_type)161 if clip_value is not None:162 clip_value = float(clip_value)163 164 total_norm = 0165 for p in parameters:166 param_norm = p.grad.data.norm(norm_type)167 total_norm += param_norm.item() ** norm_type168 if clip_value is not None:169 p.grad.data.clamp_(min=-clip_value, max=clip_value)170 total_norm = total_norm ** (1. / norm_type)171 return total_norm172 