commons.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. import math
  2. import numpy as np
  3. import torch
  4. from torch import nn
  5. from torch.nn import functional as F
  6. def 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. def get_padding(kernel_size, dilation=1):
  11. return int((kernel_size * dilation - dilation) / 2)
  12. def convert_pad_shape(pad_shape):
  13. l = pad_shape[::-1]
  14. pad_shape = [item for sublist in l for item in sublist]
  15. return pad_shape
  16. def intersperse(lst, item):
  17. result = [item] * (len(lst) * 2 + 1)
  18. result[1::2] = lst
  19. return result
  20. def kl_divergence(m_p, logs_p, m_q, logs_q):
  21. """KL(P||Q)"""
  22. kl = (logs_q - logs_p) - 0.5
  23. kl += (
  24. 0.5 * (torch.exp(2.0 * logs_p) + ((m_p - m_q) ** 2)) * torch.exp(-2.0 * logs_q)
  25. )
  26. return kl
  27. def rand_gumbel(shape):
  28. """Sample from the Gumbel distribution, protect from overflows."""
  29. uniform_samples = torch.rand(shape) * 0.99998 + 0.00001
  30. return -torch.log(-torch.log(uniform_samples))
  31. def rand_gumbel_like(x):
  32. g = rand_gumbel(x.size()).to(dtype=x.dtype, device=x.device)
  33. return g
  34. def slice_segments(x, ids_str, segment_size=4):
  35. ret = torch.zeros_like(x[:, :, :segment_size])
  36. for i in range(x.size(0)):
  37. idx_str = ids_str[i]
  38. idx_end = idx_str + segment_size
  39. ret[i] = x[i, :, idx_str:idx_end]
  40. return ret
  41. def rand_slice_segments(x, x_lengths=None, segment_size=4):
  42. b, d, t = x.size()
  43. if x_lengths is None:
  44. x_lengths = t
  45. ids_str_max = x_lengths - segment_size + 1
  46. ids_str = (torch.rand([b]).to(device=x.device) * ids_str_max).to(dtype=torch.long)
  47. ret = slice_segments(x, ids_str, segment_size)
  48. return ret, ids_str
  49. def get_timing_signal_1d(length, channels, min_timescale=1.0, max_timescale=1.0e4):
  50. position = torch.arange(length, dtype=torch.float)
  51. num_timescales = channels // 2
  52. log_timescale_increment = math.log(float(max_timescale) / float(min_timescale)) / (
  53. num_timescales - 1
  54. )
  55. inv_timescales = min_timescale * torch.exp(
  56. torch.arange(num_timescales, dtype=torch.float) * -log_timescale_increment
  57. )
  58. scaled_time = position.unsqueeze(0) * inv_timescales.unsqueeze(1)
  59. signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], 0)
  60. signal = F.pad(signal, [0, 0, 0, channels % 2])
  61. signal = signal.view(1, channels, length)
  62. return signal
  63. def add_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4):
  64. b, channels, length = x.size()
  65. signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
  66. return x + signal.to(dtype=x.dtype, device=x.device)
  67. def cat_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4, axis=1):
  68. b, channels, length = x.size()
  69. signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
  70. return torch.cat([x, signal.to(dtype=x.dtype, device=x.device)], axis)
  71. def subsequent_mask(length):
  72. mask = torch.tril(torch.ones(length, length)).unsqueeze(0).unsqueeze(0)
  73. return mask
  74. @torch.jit.script
  75. def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
  76. n_channels_int = n_channels[0]
  77. in_act = input_a + input_b
  78. t_act = torch.tanh(in_act[:, :n_channels_int, :])
  79. s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
  80. acts = t_act * s_act
  81. return acts
  82. def convert_pad_shape(pad_shape):
  83. l = pad_shape[::-1]
  84. pad_shape = [item for sublist in l for item in sublist]
  85. return pad_shape
  86. def shift_1d(x):
  87. x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [1, 0]]))[:, :, :-1]
  88. return x
  89. def sequence_mask(length, max_length=None):
  90. if max_length is None:
  91. max_length = length.max()
  92. x = torch.arange(max_length, dtype=length.dtype, device=length.device)
  93. return x.unsqueeze(0) < length.unsqueeze(1)
  94. def generate_path(duration, mask):
  95. """
  96. duration: [b, 1, t_x]
  97. mask: [b, 1, t_y, t_x]
  98. """
  99. device = duration.device
  100. b, _, t_y, t_x = mask.shape
  101. cum_duration = torch.cumsum(duration, -1)
  102. cum_duration_flat = cum_duration.view(b * t_x)
  103. path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype)
  104. path = path.view(b, t_x, t_y)
  105. path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1]
  106. path = path.unsqueeze(1).transpose(2, 3) * mask
  107. return path
  108. def clip_grad_value_(parameters, clip_value, norm_type=2):
  109. if isinstance(parameters, torch.Tensor):
  110. parameters = [parameters]
  111. parameters = list(filter(lambda p: p.grad is not None, parameters))
  112. norm_type = float(norm_type)
  113. if clip_value is not None:
  114. clip_value = float(clip_value)
  115. total_norm = 0
  116. for p in parameters:
  117. param_norm = p.grad.data.norm(norm_type)
  118. total_norm += param_norm.item() ** norm_type
  119. if clip_value is not None:
  120. p.grad.data.clamp_(min=-clip_value, max=clip_value)
  121. total_norm = total_norm ** (1.0 / norm_type)
  122. return total_norm
  123. def squeeze(x, x_mask=None, n_sqz=2):
  124. b, c, t = x.size()
  125. t = (t // n_sqz) * n_sqz
  126. x = x[:, :, :t]
  127. x_sqz = x.view(b, c, t // n_sqz, n_sqz)
  128. x_sqz = x_sqz.permute(0, 3, 1, 2).contiguous().view(b, c * n_sqz, t // n_sqz)
  129. if x_mask is not None:
  130. x_mask = x_mask[:, :, n_sqz - 1 :: n_sqz]
  131. else:
  132. x_mask = torch.ones(b, 1, t // n_sqz).to(device=x.device, dtype=x.dtype)
  133. return x_sqz * x_mask, x_mask
  134. def unsqueeze(x, x_mask=None, n_sqz=2):
  135. b, c, t = x.size()
  136. x_unsqz = x.view(b, n_sqz, c // n_sqz, t)
  137. x_unsqz = x_unsqz.permute(0, 2, 3, 1).contiguous().view(b, c // n_sqz, t * n_sqz)
  138. if x_mask is not None:
  139. x_mask = x_mask.unsqueeze(-1).repeat(1, 1, 1, n_sqz).view(b, 1, t * n_sqz)
  140. else:
  141. x_mask = torch.ones(b, 1, t * n_sqz).to(device=x.device, dtype=x.dtype)
  142. return x_unsqz * x_mask, x_mask