fighter-programmer/voicegen
0
1import math2import torch3from torch.nn import functional as F4import torch.jit5 6 7def script_method(fn, _rcb=None):8 return fn9 10 11def script(obj, optimize=True, _frames_up=0, _rcb=None):12 return obj13 14 15torch.jit.script_method = script_method16torch.jit.script = script17 18 19def init_weights(m, mean=0.0, std=0.01):20 classname = m.__class__.__name__21 if classname.find("Conv") != -1:22 m.weight.data.normal_(mean, std)23 24 25def get_padding(kernel_size, dilation=1):26 return int((kernel_size*dilation - dilation)/2)27 28 29def intersperse(lst, item):30 result = [item] * (len(lst) * 2 + 1)31 result[1::2] = lst32 return result33 34 35def slice_segments(x, ids_str, segment_size=4):36 ret = torch.zeros_like(x[:, :, :segment_size])37 for i in range(x.size(0)):38 idx_str = ids_str[i]39 idx_end = idx_str + segment_size40 ret[i] = x[i, :, idx_str:idx_end]41 return ret42 43 44def rand_slice_segments(x, x_lengths=None, segment_size=4):45 b, d, t = x.size()46 if x_lengths is None:47 x_lengths = t48 ids_str_max = x_lengths - segment_size + 149 ids_str = (torch.rand([b]).to(device=x.device) * ids_str_max).to(dtype=torch.long)50 ret = slice_segments(x, ids_str, segment_size)51 return ret, ids_str52 53 54def subsequent_mask(length):55 mask = torch.tril(torch.ones(length, length)).unsqueeze(0).unsqueeze(0)56 return mask57 58 59@torch.jit.script60def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):61 n_channels_int = n_channels[0]62 in_act = input_a + input_b63 t_act = torch.tanh(in_act[:, :n_channels_int, :])64 s_act = torch.sigmoid(in_act[:, n_channels_int:, :])65 acts = t_act * s_act66 return acts67 68 69def convert_pad_shape(pad_shape):70 l = pad_shape[::-1]71 pad_shape = [item for sublist in l for item in sublist]72 return pad_shape73 74 75def sequence_mask(length, max_length=None):76 if max_length is None:77 max_length = length.max()78 x = torch.arange(max_length, dtype=length.dtype, device=length.device)79 return x.unsqueeze(0) < length.unsqueeze(1)80 81 82def generate_path(duration, mask):83 """84 duration: [b, 1, t_x]85 mask: [b, 1, t_y, t_x]86 """87 device = duration.device88 89 b, _, t_y, t_x = mask.shape90 cum_duration = torch.cumsum(duration, -1)91 92 cum_duration_flat = cum_duration.view(b * t_x)93 path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype)94 path = path.view(b, t_x, t_y)95 path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1]96 path = path.unsqueeze(1).transpose(2,3) * mask97 return path98 