commons.py 5.7 KB

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