Clicko777/RVC_HFv2
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 kl_divergence(m_p, logs_p, m_q, logs_q):25 """KL(P||Q)"""26 kl = (logs_q - logs_p) - 0.527 kl += (28 0.5 * (torch.exp(2.0 * logs_p) + ((m_p - m_q) ** 2)) * torch.exp(-2.0 * logs_q)29 )30 return kl31 32 33def rand_gumbel(shape):34 """Sample from the Gumbel distribution, protect from overflows."""35 uniform_samples = torch.rand(shape) * 0.99998 + 0.0000136 return -torch.log(-torch.log(uniform_samples))37 38 39def rand_gumbel_like(x):40 g = rand_gumbel(x.size()).to(dtype=x.dtype, device=x.device)41 return g42 43 44def slice_segments(x, ids_str, segment_size=4):45 ret = torch.zeros_like(x[:, :, :segment_size])46 for i in range(x.size(0)):47 idx_str = ids_str[i]48 idx_end = idx_str + segment_size49 ret[i] = x[i, :, idx_str:idx_end]50 return ret51 52 53def slice_segments2(x, ids_str, segment_size=4):54 ret = torch.zeros_like(x[:, :segment_size])55 for i in range(x.size(0)):56 idx_str = ids_str[i]57 idx_end = idx_str + segment_size58 ret[i] = x[i, idx_str:idx_end]59 return ret60 61 62def rand_slice_segments(x, x_lengths=None, segment_size=4):63 b, d, t = x.size()64 if x_lengths is None:65 x_lengths = t66 ids_str_max = x_lengths - segment_size + 167 ids_str = (torch.rand([b]).to(device=x.device) * ids_str_max).to(dtype=torch.long)68 ret = slice_segments(x, ids_str, segment_size)69 return ret, ids_str70 71 72def get_timing_signal_1d(length, channels, min_timescale=1.0, max_timescale=1.0e4):73 position = torch.arange(length, dtype=torch.float)74 num_timescales = channels // 275 log_timescale_increment = math.log(float(max_timescale) / float(min_timescale)) / (76 num_timescales - 177 )78 inv_timescales = min_timescale * torch.exp(79 torch.arange(num_timescales, dtype=torch.float) * -log_timescale_increment80 )81 scaled_time = position.unsqueeze(0) * inv_timescales.unsqueeze(1)82 signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], 0)83 signal = F.pad(signal, [0, 0, 0, channels % 2])84 signal = signal.view(1, channels, length)85 return signal86 87 88def add_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4):89 b, channels, length = x.size()90 signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)91 return x + signal.to(dtype=x.dtype, device=x.device)92 93 94def cat_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4, axis=1):95 b, channels, length = x.size()96 signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)97 return torch.cat([x, signal.to(dtype=x.dtype, device=x.device)], axis)98 99 100def subsequent_mask(length):101 mask = torch.tril(torch.ones(length, length)).unsqueeze(0).unsqueeze(0)102 return mask103 104 105@torch.jit.script106def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):107 n_channels_int = n_channels[0]108 in_act = input_a + input_b109 t_act = torch.tanh(in_act[:, :n_channels_int, :])110 s_act = torch.sigmoid(in_act[:, n_channels_int:, :])111 acts = t_act * s_act112 return acts113 114 115def convert_pad_shape(pad_shape):116 l = pad_shape[::-1]117 pad_shape = [item for sublist in l for item in sublist]118 return pad_shape119 120 121def shift_1d(x):122 x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [1, 0]]))[:, :, :-1]123 return x124 125 126def sequence_mask(length, max_length=None):127 if max_length is None:128 max_length = length.max()129 x = torch.arange(max_length, dtype=length.dtype, device=length.device)130 return x.unsqueeze(0) < length.unsqueeze(1)131 132 133def generate_path(duration, mask):134 """135 duration: [b, 1, t_x]136 mask: [b, 1, t_y, t_x]137 """138 device = duration.device139 140 b, _, t_y, t_x = mask.shape141 cum_duration = torch.cumsum(duration, -1)142 143 cum_duration_flat = cum_duration.view(b * t_x)144 path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype)145 path = path.view(b, t_x, t_y)146 path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1]147 path = path.unsqueeze(1).transpose(2, 3) * mask148 return path149 150 151def clip_grad_value_(parameters, clip_value, norm_type=2):152 if isinstance(parameters, torch.Tensor):153 parameters = [parameters]154 parameters = list(filter(lambda p: p.grad is not None, parameters))155 norm_type = float(norm_type)156 if clip_value is not None:157 clip_value = float(clip_value)158 159 total_norm = 0160 for p in parameters:161 param_norm = p.grad.data.norm(norm_type)162 total_norm += param_norm.item() ** norm_type163 if clip_value is not None:164 p.grad.data.clamp_(min=-clip_value, max=clip_value)165 total_norm = total_norm ** (1.0 / norm_type)166 return total_norm167 