1
0

common.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  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. import random
  18. from typing import List
  19. import numpy as np
  20. import torch
  21. IGNORE_ID = -1
  22. def pad_list(xs: List[torch.Tensor], pad_value: int):
  23. """Perform padding for the list of tensors.
  24. Args:
  25. xs (List): List of Tensors [(T_1, `*`), (T_2, `*`), ..., (T_B, `*`)].
  26. pad_value (float): Value for padding.
  27. Returns:
  28. Tensor: Padded tensor (B, Tmax, `*`).
  29. Examples:
  30. >>> x = [torch.ones(4), torch.ones(2), torch.ones(1)]
  31. >>> x
  32. [tensor([1., 1., 1., 1.]), tensor([1., 1.]), tensor([1.])]
  33. >>> pad_list(x, 0)
  34. tensor([[1., 1., 1., 1.],
  35. [1., 1., 0., 0.],
  36. [1., 0., 0., 0.]])
  37. """
  38. max_len = max([len(item) for item in xs])
  39. batchs = len(xs)
  40. ndim = xs[0].ndim
  41. if ndim == 1:
  42. pad_res = torch.zeros(batchs,
  43. max_len,
  44. dtype=xs[0].dtype,
  45. device=xs[0].device)
  46. elif ndim == 2:
  47. pad_res = torch.zeros(batchs,
  48. max_len,
  49. xs[0].shape[1],
  50. dtype=xs[0].dtype,
  51. device=xs[0].device)
  52. elif ndim == 3:
  53. pad_res = torch.zeros(batchs,
  54. max_len,
  55. xs[0].shape[1],
  56. xs[0].shape[2],
  57. dtype=xs[0].dtype,
  58. device=xs[0].device)
  59. else:
  60. raise ValueError(f"Unsupported ndim: {ndim}")
  61. pad_res.fill_(pad_value)
  62. for i in range(batchs):
  63. pad_res[i, :len(xs[i])] = xs[i]
  64. return pad_res
  65. def th_accuracy(pad_outputs: torch.Tensor, pad_targets: torch.Tensor,
  66. ignore_label: int) -> torch.Tensor:
  67. """Calculate accuracy.
  68. Args:
  69. pad_outputs (Tensor): Prediction tensors (B * Lmax, D).
  70. pad_targets (LongTensor): Target label tensors (B, Lmax).
  71. ignore_label (int): Ignore label id.
  72. Returns:
  73. torch.Tensor: Accuracy value (0.0 - 1.0).
  74. """
  75. pad_pred = pad_outputs.view(pad_targets.size(0), pad_targets.size(1),
  76. pad_outputs.size(1)).argmax(2)
  77. mask = pad_targets != ignore_label
  78. numerator = torch.sum(
  79. pad_pred.masked_select(mask) == pad_targets.masked_select(mask))
  80. denominator = torch.sum(mask)
  81. return (numerator / denominator).detach()
  82. def get_padding(kernel_size, dilation=1):
  83. return int((kernel_size * dilation - dilation) / 2)
  84. def init_weights(m, mean=0.0, std=0.01):
  85. classname = m.__class__.__name__
  86. if classname.find("Conv") != -1:
  87. m.weight.data.normal_(mean, std)
  88. # Repetition Aware Sampling in VALL-E 2
  89. def ras_sampling(weighted_scores, decoded_tokens, sampling, top_p=0.8, top_k=25, win_size=10, tau_r=0.1):
  90. top_ids = nucleus_sampling(weighted_scores, top_p=top_p, top_k=top_k)
  91. rep_num = (torch.tensor(decoded_tokens[-win_size:]).to(weighted_scores.device) == top_ids).sum().item()
  92. if rep_num >= win_size * tau_r:
  93. top_ids = random_sampling(weighted_scores, decoded_tokens, sampling)
  94. return top_ids
  95. def nucleus_sampling(weighted_scores, top_p=0.8, top_k=25):
  96. prob, indices = [], []
  97. cum_prob = 0.0
  98. sorted_value, sorted_idx = weighted_scores.softmax(dim=0).sort(descending=True, stable=True)
  99. for i in range(len(sorted_idx)):
  100. # sampling both top-p and numbers.
  101. if cum_prob < top_p and len(prob) < top_k:
  102. cum_prob += sorted_value[i]
  103. prob.append(sorted_value[i])
  104. indices.append(sorted_idx[i])
  105. else:
  106. break
  107. prob = torch.tensor(prob).to(weighted_scores)
  108. indices = torch.tensor(indices, dtype=torch.long).to(weighted_scores.device)
  109. top_ids = indices[prob.multinomial(1, replacement=True)]
  110. return top_ids
  111. def random_sampling(weighted_scores, decoded_tokens, sampling):
  112. top_ids = weighted_scores.softmax(dim=0).multinomial(1, replacement=True)
  113. return top_ids
  114. def fade_in_out(fade_in_mel, fade_out_mel, window):
  115. device = fade_in_mel.device
  116. fade_in_mel, fade_out_mel = fade_in_mel.cpu(), fade_out_mel.cpu()
  117. mel_overlap_len = int(window.shape[0] / 2)
  118. if fade_in_mel.device == torch.device('cpu'):
  119. fade_in_mel = fade_in_mel.clone()
  120. fade_in_mel[..., :mel_overlap_len] = fade_in_mel[..., :mel_overlap_len] * window[:mel_overlap_len] + \
  121. fade_out_mel[..., -mel_overlap_len:] * window[mel_overlap_len:]
  122. return fade_in_mel.to(device)
  123. def set_all_random_seed(seed):
  124. random.seed(seed)
  125. np.random.seed(seed)
  126. torch.manual_seed(seed)
  127. torch.cuda.manual_seed_all(seed)
  128. def mask_to_bias(mask: torch.Tensor, dtype: torch.dtype) -> torch.Tensor:
  129. assert mask.dtype == torch.bool
  130. assert dtype in [torch.float32, torch.bfloat16, torch.float16]
  131. mask = mask.to(dtype)
  132. # attention mask bias
  133. # NOTE(Mddct): torch.finfo jit issues
  134. # chunk_masks = (1.0 - chunk_masks) * torch.finfo(dtype).min
  135. mask = (1.0 - mask) * -1.0e+10
  136. return mask