CoolFace
Apppublic

surfmore/SimpleRVC

sourceHugging Facemitupdated 3y agoView on Hugging Face
0likes
commons.py165 linesDownload Raw Back to infer_pack
1import math2import torch3from torch.nn import functional as F4 5 6def init_weights(m, mean=0.0, std=0.01):7    classname = m.__class__.__name__8    if classname.find("Conv") != -1:9        m.weight.data.normal_(mean, std)10 11 12def get_padding(kernel_size, dilation=1):13    return int((kernel_size * dilation - dilation) / 2)14 15 16def convert_pad_shape(pad_shape):17    l = pad_shape[::-1]18    pad_shape = [item for sublist in l for item in sublist]19    return pad_shape20 21 22def kl_divergence(m_p, logs_p, m_q, logs_q):23    """KL(P||Q)"""24    kl = (logs_q - logs_p) - 0.525    kl += (26        0.5 * (torch.exp(2.0 * logs_p) + ((m_p - m_q) ** 2)) * torch.exp(-2.0 * logs_q)27    )28    return kl29 30 31def rand_gumbel(shape):32    """Sample from the Gumbel distribution, protect from overflows."""33    uniform_samples = torch.rand(shape) * 0.99998 + 0.0000134    return -torch.log(-torch.log(uniform_samples))35 36 37def rand_gumbel_like(x):38    g = rand_gumbel(x.size()).to(dtype=x.dtype, device=x.device)39    return g40 41 42def slice_segments(x, ids_str, segment_size=4):43    ret = torch.zeros_like(x[:, :, :segment_size])44    for i in range(x.size(0)):45        idx_str = ids_str[i]46        idx_end = idx_str + segment_size47        ret[i] = x[i, :, idx_str:idx_end]48    return ret49 50 51def slice_segments2(x, ids_str, segment_size=4):52    ret = torch.zeros_like(x[:, :segment_size])53    for i in range(x.size(0)):54        idx_str = ids_str[i]55        idx_end = idx_str + segment_size56        ret[i] = x[i, idx_str:idx_end]57    return ret58 59 60def rand_slice_segments(x, x_lengths=None, segment_size=4):61    b, d, t = x.size()62    if x_lengths is None:63        x_lengths = t64    ids_str_max = x_lengths - segment_size + 165    ids_str = (torch.rand([b]).to(device=x.device) * ids_str_max).to(dtype=torch.long)66    ret = slice_segments(x, ids_str, segment_size)67    return ret, ids_str68 69 70def get_timing_signal_1d(length, channels, min_timescale=1.0, max_timescale=1.0e4):71    position = torch.arange(length, dtype=torch.float)72    num_timescales = channels // 273    log_timescale_increment = math.log(float(max_timescale) / float(min_timescale)) / (74        num_timescales - 175    )76    inv_timescales = min_timescale * torch.exp(77        torch.arange(num_timescales, dtype=torch.float) * -log_timescale_increment78    )79    scaled_time = position.unsqueeze(0) * inv_timescales.unsqueeze(1)80    signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], 0)81    signal = F.pad(signal, [0, 0, 0, channels % 2])82    signal = signal.view(1, channels, length)83    return signal84 85 86def add_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4):87    b, channels, length = x.size()88    signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)89    return x + signal.to(dtype=x.dtype, device=x.device)90 91 92def cat_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4, axis=1):93    b, channels, length = x.size()94    signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)95    return torch.cat([x, signal.to(dtype=x.dtype, device=x.device)], axis)96 97 98def subsequent_mask(length):99    mask = torch.tril(torch.ones(length, length)).unsqueeze(0).unsqueeze(0)100    return mask101 102 103@torch.jit.script104def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):105    n_channels_int = n_channels[0]106    in_act = input_a + input_b107    t_act = torch.tanh(in_act[:, :n_channels_int, :])108    s_act = torch.sigmoid(in_act[:, n_channels_int:, :])109    acts = t_act * s_act110    return acts111 112 113def convert_pad_shape(pad_shape):114    l = pad_shape[::-1]115    pad_shape = [item for sublist in l for item in sublist]116    return pad_shape117 118 119def shift_1d(x):120    x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [1, 0]]))[:, :, :-1]121    return x122 123 124def sequence_mask(length, max_length=None):125    if max_length is None:126        max_length = length.max()127    x = torch.arange(max_length, dtype=length.dtype, device=length.device)128    return x.unsqueeze(0) < length.unsqueeze(1)129 130 131def generate_path(duration, mask):132    """133    duration: [b, 1, t_x]134    mask: [b, 1, t_y, t_x]135    """136    device = duration.device137 138    b, _, t_y, t_x = mask.shape139    cum_duration = torch.cumsum(duration, -1)140 141    cum_duration_flat = cum_duration.view(b * t_x)142    path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype)143    path = path.view(b, t_x, t_y)144    path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1]145    path = path.unsqueeze(1).transpose(2, 3) * mask146    return path147 148 149def clip_grad_value_(parameters, clip_value, norm_type=2):150    if isinstance(parameters, torch.Tensor):151        parameters = [parameters]152    parameters = list(filter(lambda p: p.grad is not None, parameters))153    norm_type = float(norm_type)154    if clip_value is not None:155        clip_value = float(clip_value)156 157    total_norm = 0158    for p in parameters:159        param_norm = p.grad.data.norm(norm_type)160        total_norm += param_norm.item() ** norm_type161        if clip_value is not None:162            p.grad.data.clamp_(min=-clip_value, max=clip_value)163    total_norm = total_norm ** (1.0 / norm_type)164    return total_norm165