CoolFace
Apppublic

ORI-Muchim/BlueArchiveTTS

sourceHugging Facemitupdated 10mo agoView on Hugging Face
58likes
commons.py162 linesDownload Raw Back to root
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 get_timing_signal_1d(68    length, channels, min_timescale=1.0, max_timescale=1.0e4):69  position = torch.arange(length, dtype=torch.float)70  num_timescales = channels // 271  log_timescale_increment = (72      math.log(float(max_timescale) / float(min_timescale)) /73      (num_timescales - 1))74  inv_timescales = min_timescale * torch.exp(75      torch.arange(num_timescales, dtype=torch.float) * -log_timescale_increment)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  l = pad_shape[::-1]112  pad_shape = [item for sublist in l 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  device = duration.device134  135  b, _, t_y, t_x = mask.shape136  cum_duration = torch.cumsum(duration, -1)137  138  cum_duration_flat = cum_duration.view(b * t_x)139  path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype)140  path = path.view(b, t_x, t_y)141  path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1]142  path = path.unsqueeze(1).transpose(2,3) * mask143  return path144 145 146def clip_grad_value_(parameters, clip_value, norm_type=2):147  if isinstance(parameters, torch.Tensor):148    parameters = [parameters]149  parameters = list(filter(lambda p: p.grad is not None, parameters))150  norm_type = float(norm_type)151  if clip_value is not None:152    clip_value = float(clip_value)153 154  total_norm = 0155  for p in parameters:156    param_norm = p.grad.data.norm(norm_type)157    total_norm += param_norm.item() ** norm_type158    if clip_value is not None:159      p.grad.data.clamp_(min=-clip_value, max=clip_value)160  total_norm = total_norm ** (1. / norm_type)161  return total_norm162