CoolFace
Apppublic

6Simple9/ChatTTS-OpenVoice

sourceHugging Facemitupdated 2y agoView on Hugging Face
9likes
commons.py161 linesDownload Raw Back to OpenVoice
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    layer = pad_shape[::-1]18    pad_shape = [item for sublist in layer for item in sublist]19    return pad_shape20 21 22def intersperse(lst, item):23    result = [item] * (len(lst) * 2 + 1)24    result[1::2] = lst25    return result26 27 28def kl_divergence(m_p, logs_p, m_q, logs_q):29    """KL(P||Q)"""30    kl = (logs_q - logs_p) - 0.531    kl += (32        0.5 * (torch.exp(2.0 * logs_p) + ((m_p - m_q) ** 2)) * torch.exp(-2.0 * logs_q)33    )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 get_timing_signal_1d(length, channels, min_timescale=1.0, max_timescale=1.0e4):68    position = torch.arange(length, dtype=torch.float)69    num_timescales = channels // 270    log_timescale_increment = math.log(float(max_timescale) / float(min_timescale)) / (71        num_timescales - 172    )73    inv_timescales = min_timescale * torch.exp(74        torch.arange(num_timescales, dtype=torch.float) * -log_timescale_increment75    )76    scaled_time = position.unsqueeze(0) * inv_timescales.unsqueeze(1)77    signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], 0)78    signal = F.pad(signal, [0, 0, 0, channels % 2])79    signal = signal.view(1, channels, length)80    return signal81 82 83def add_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4):84    b, channels, length = x.size()85    signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)86    return x + signal.to(dtype=x.dtype, device=x.device)87 88 89def cat_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4, axis=1):90    b, channels, length = x.size()91    signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)92    return torch.cat([x, signal.to(dtype=x.dtype, device=x.device)], axis)93 94 95def subsequent_mask(length):96    mask = torch.tril(torch.ones(length, length)).unsqueeze(0).unsqueeze(0)97    return mask98 99 100@torch.jit.script101def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):102    n_channels_int = n_channels[0]103    in_act = input_a + input_b104    t_act = torch.tanh(in_act[:, :n_channels_int, :])105    s_act = torch.sigmoid(in_act[:, n_channels_int:, :])106    acts = t_act * s_act107    return acts108 109 110def convert_pad_shape(pad_shape):111    layer = pad_shape[::-1]112    pad_shape = [item for sublist in layer for item in sublist]113    return pad_shape114 115 116def shift_1d(x):117    x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [1, 0]]))[:, :, :-1]118    return x119 120 121def sequence_mask(length, max_length=None):122    if max_length is None:123        max_length = length.max()124    x = torch.arange(max_length, dtype=length.dtype, device=length.device)125    return x.unsqueeze(0) < length.unsqueeze(1)126 127 128def generate_path(duration, mask):129    """130    duration: [b, 1, t_x]131    mask: [b, 1, t_y, t_x]132    """133 134    b, _, t_y, t_x = mask.shape135    cum_duration = torch.cumsum(duration, -1)136 137    cum_duration_flat = cum_duration.view(b * t_x)138    path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype)139    path = path.view(b, t_x, t_y)140    path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1]141    path = path.unsqueeze(1).transpose(2, 3) * mask142    return path143 144 145def clip_grad_value_(parameters, clip_value, norm_type=2):146    if isinstance(parameters, torch.Tensor):147        parameters = [parameters]148    parameters = list(filter(lambda p: p.grad is not None, parameters))149    norm_type = float(norm_type)150    if clip_value is not None:151        clip_value = float(clip_value)152 153    total_norm = 0154    for p in parameters:155        param_norm = p.grad.data.norm(norm_type)156        total_norm += param_norm.item() ** norm_type157        if clip_value is not None:158            p.grad.data.clamp_(min=-clip_value, max=clip_value)159    total_norm = total_norm ** (1.0 / norm_type)160    return total_norm161