common.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. # Copyright (c) 2020 Mobvoi Inc (Binbin Zhang)
  2. # 2024 Alibaba Inc (authors: Xiang Lyu)
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. # Modified from ESPnet(https://github.com/espnet/espnet)
  16. """Unility functions for Transformer."""
  17. from typing import List
  18. import torch
  19. IGNORE_ID = -1
  20. def pad_list(xs: List[torch.Tensor], pad_value: int):
  21. """Perform padding for the list of tensors.
  22. Args:
  23. xs (List): List of Tensors [(T_1, `*`), (T_2, `*`), ..., (T_B, `*`)].
  24. pad_value (float): Value for padding.
  25. Returns:
  26. Tensor: Padded tensor (B, Tmax, `*`).
  27. Examples:
  28. >>> x = [torch.ones(4), torch.ones(2), torch.ones(1)]
  29. >>> x
  30. [tensor([1., 1., 1., 1.]), tensor([1., 1.]), tensor([1.])]
  31. >>> pad_list(x, 0)
  32. tensor([[1., 1., 1., 1.],
  33. [1., 1., 0., 0.],
  34. [1., 0., 0., 0.]])
  35. """
  36. max_len = max([len(item) for item in xs])
  37. batchs = len(xs)
  38. ndim = xs[0].ndim
  39. if ndim == 1:
  40. pad_res = torch.zeros(batchs,
  41. max_len,
  42. dtype=xs[0].dtype,
  43. device=xs[0].device)
  44. elif ndim == 2:
  45. pad_res = torch.zeros(batchs,
  46. max_len,
  47. xs[0].shape[1],
  48. dtype=xs[0].dtype,
  49. device=xs[0].device)
  50. elif ndim == 3:
  51. pad_res = torch.zeros(batchs,
  52. max_len,
  53. xs[0].shape[1],
  54. xs[0].shape[2],
  55. dtype=xs[0].dtype,
  56. device=xs[0].device)
  57. else:
  58. raise ValueError(f"Unsupported ndim: {ndim}")
  59. pad_res.fill_(pad_value)
  60. for i in range(batchs):
  61. pad_res[i, :len(xs[i])] = xs[i]
  62. return pad_res
  63. def th_accuracy(pad_outputs: torch.Tensor, pad_targets: torch.Tensor,
  64. ignore_label: int) -> torch.Tensor:
  65. """Calculate accuracy.
  66. Args:
  67. pad_outputs (Tensor): Prediction tensors (B * Lmax, D).
  68. pad_targets (LongTensor): Target label tensors (B, Lmax).
  69. ignore_label (int): Ignore label id.
  70. Returns:
  71. torch.Tensor: Accuracy value (0.0 - 1.0).
  72. """
  73. pad_pred = pad_outputs.view(pad_targets.size(0), pad_targets.size(1),
  74. pad_outputs.size(1)).argmax(2)
  75. mask = pad_targets != ignore_label
  76. numerator = torch.sum(
  77. pad_pred.masked_select(mask) == pad_targets.masked_select(mask))
  78. denominator = torch.sum(mask)
  79. return (numerator / denominator).detach()
  80. def get_padding(kernel_size, dilation=1):
  81. return int((kernel_size * dilation - dilation) / 2)
  82. def init_weights(m, mean=0.0, std=0.01):
  83. classname = m.__class__.__name__
  84. if classname.find("Conv") != -1:
  85. m.weight.data.normal_(mean, std)
  86. # Repetition Aware Sampling in VALL-E 2
  87. def ras_sampling(weighted_scores, decoded_tokens, sampling, top_p=0.8, top_k=25, win_size=10, tau_r=0.1):
  88. top_ids = nucleus_sampling(weighted_scores, top_p=top_p, top_k=top_k)
  89. rep_num = (torch.tensor(decoded_tokens[-win_size:]).to(weighted_scores.device) == top_ids).sum().item()
  90. if rep_num >= win_size * tau_r:
  91. top_ids = random_sampling(weighted_scores, decoded_tokens, sampling)
  92. return top_ids
  93. def nucleus_sampling(weighted_scores, top_p=0.8, top_k=25):
  94. prob, indices = [], []
  95. cum_prob = 0.0
  96. sorted_value, sorted_idx = weighted_scores.softmax(dim=0).sort(descending=True, stable=True)
  97. for i in range(len(sorted_idx)):
  98. # sampling both top-p and numbers.
  99. if cum_prob < top_p and len(prob) < top_k:
  100. cum_prob += sorted_value[i]
  101. prob.append(sorted_value[i])
  102. indices.append(sorted_idx[i])
  103. else:
  104. break
  105. prob = torch.tensor(prob).to(weighted_scores)
  106. indices = torch.tensor(indices, dtype=torch.long).to(weighted_scores.device)
  107. top_ids = indices[prob.multinomial(1, replacement=True)]
  108. return top_ids
  109. def random_sampling(weighted_scores, decoded_tokens, sampling):
  110. top_ids = weighted_scores.softmax(dim=0).multinomial(1, replacement=True)
  111. return top_ids
  112. def fade_in_out(fade_in_mel, fade_out_mel, window):
  113. device = fade_in_mel.device
  114. fade_in_mel, fade_out_mel = fade_in_mel.cpu(), fade_out_mel.cpu()
  115. mel_overlap_len = int(window.shape[0] / 2)
  116. fade_in_mel[:, :, :mel_overlap_len] = fade_in_mel[:, :, :mel_overlap_len] * window[:mel_overlap_len] + fade_out_mel[:, :, -mel_overlap_len:] * window[mel_overlap_len:]
  117. return fade_in_mel.to(device)