CoolFace
Apppublic

Aloento/9Nine-PITS

sourceHugging Faceagpl-3.0updated 4y agoView on Hugging Face
1likes
commons.py193 linesDownload Raw Back to root
1# from https://github.com/jaywalnut310/vits2import math3 4import torch5from 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 intersperse_with_language_id(text, lang, item):31  n = len(text)32  _text = [item] * (2 * n + 1)33  _lang = [None] * (2 * n + 1)34  _text[1::2] = text35  _lang[1::2] = lang36  _lang[::2] = lang + [lang[-1]]37 38  return _text, _lang39 40 41def kl_divergence(m_p, logs_p, m_q, logs_q):42  """KL(P||Q)"""43  kl = (logs_q - logs_p) - 0.544  kl += 0.5 * (torch.exp(2. * logs_p) + ((m_p - m_q) ** 2)) * torch.exp(-2. * logs_q)45  return kl46 47 48def rand_gumbel(shape):49  """Sample from the Gumbel distribution, protect from overflows."""50  uniform_samples = torch.rand(shape) * 0.99998 + 0.0000151  return -torch.log(-torch.log(uniform_samples))52 53 54def rand_gumbel_like(x):55  g = rand_gumbel(x.size()).to(dtype=x.dtype, device=x.device)56  return g57 58 59def slice_segments(x, ids_str, segment_size=4):60  ret = torch.zeros_like(x[:, :, :segment_size])61  for i in range(x.size(0)):62    idx_str = ids_str[i]63    idx_end = idx_str + segment_size64    ret[i] = x[i, :, idx_str:idx_end]65  return ret66 67 68def rand_slice_segments(x, x_lengths=None, segment_size=4):69  b, d, t = x.size()70  if x_lengths is None:71    x_lengths = t72  ids_str_max = x_lengths - segment_size + 173  ids_str = (torch.rand([b]).to(device=x.device)74             * ids_str_max).to(dtype=torch.long)75  ids_str = torch.max(torch.zeros(ids_str.size()).to(ids_str.device), ids_str).to(dtype=torch.long)76  ret = slice_segments(x, ids_str, segment_size)77  return ret, ids_str78 79 80def rand_slice_segments_for_cat(x, x_lengths=None, segment_size=4):81  b, d, t = x.size()82  if x_lengths is None:83    x_lengths = t84  ids_str_max = x_lengths - segment_size + 185  ids_str = torch.rand([b // 2]).to(device=x.device)86  ids_str = (torch.cat([ids_str, ids_str], dim=0)87             * ids_str_max).to(dtype=torch.long)88  ids_str = torch.max(torch.zeros(ids_str.size()).to(ids_str.device), ids_str).to(dtype=torch.long)89  ret = slice_segments(x, ids_str, segment_size)90  return ret, ids_str91 92 93def get_timing_signal_1d(94    length, channels, min_timescale=1.0, max_timescale=1.0e4):95  position = torch.arange(length, dtype=torch.float)96  num_timescales = channels // 297  log_timescale_increment = (98      math.log(float(max_timescale) / float(min_timescale)) / (num_timescales - 1)99  )100  inv_timescales = min_timescale * torch.exp(101    torch.arange(num_timescales, dtype=torch.float) * -log_timescale_increment102  )103  scaled_time = position.unsqueeze(0) * inv_timescales.unsqueeze(1)104  signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], 0)105  signal = F.pad(signal, [0, 0, 0, channels % 2])106  signal = signal.view(1, channels, length)107  return signal108 109 110def add_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4):111  b, channels, length = x.size()112  signal = get_timing_signal_1d(113    length, channels, min_timescale, max_timescale114  )115  return x + signal.to(dtype=x.dtype, device=x.device)116 117 118def cat_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4, axis=1):119  b, channels, length = x.size()120  signal = get_timing_signal_1d(121    length, channels, min_timescale, max_timescale122  )123  return torch.cat([x, signal.to(dtype=x.dtype, device=x.device)], axis)124 125 126def subsequent_mask(length):127  mask = torch.tril(torch.ones(length, length)).unsqueeze(0).unsqueeze(0)128  return mask129 130 131@torch.jit.script132def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):133  n_channels_int = n_channels[0]134  in_act = input_a + input_b135  t_act = torch.tanh(in_act[:, :n_channels_int, :])136  s_act = torch.sigmoid(in_act[:, n_channels_int:, :])137  acts = t_act * s_act138  return acts139 140 141def convert_pad_shape(pad_shape):142  l = pad_shape[::-1]143  pad_shape = [item for sublist in l for item in sublist]144  return pad_shape145 146 147def shift_1d(x):148  x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [1, 0]]))[:, :, :-1]149  return x150 151 152def sequence_mask(length, max_length=None):153  if max_length is None:154    max_length = length.max()155  x = torch.arange(max_length, dtype=length.dtype, device=length.device)156  return x.unsqueeze(0) < length.unsqueeze(1)157 158 159def generate_path(duration, mask):160  """161  duration: [b, 1, t_x]162  mask: [b, 1, t_y, t_x]163  """164  device = duration.device165 166  b, _, t_y, t_x = mask.shape167  cum_duration = torch.cumsum(duration, -1)168 169  cum_duration_flat = cum_duration.view(b * t_x)170  path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype)171  path = path.view(b, t_x, t_y)172  path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1]173  path = path.unsqueeze(1).transpose(2, 3) * mask174  return path175 176 177def clip_grad_value_(parameters, clip_value, norm_type=2):178  if isinstance(parameters, torch.Tensor):179    parameters = [parameters]180  parameters = list(filter(lambda p: p.grad is not None, parameters))181  norm_type = float(norm_type)182  if clip_value is not None:183    clip_value = float(clip_value)184 185  total_norm = 0186  for p in parameters:187    param_norm = p.grad.data.norm(norm_type)188    total_norm += param_norm.item() ** norm_type189    if clip_value is not None:190      p.grad.data.clamp_(min=-clip_value, max=clip_value)191  total_norm = total_norm ** (1. / norm_type)192  return total_norm193