common.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. # Copyright (c) 2020 Mobvoi Inc (Binbin Zhang)
  2. # 2024 Alibaba Inc (authors: Xiang Lyu)
  3. # 2025 Alibaba Inc (authors: Xiang Lyu, Bofan Zhou)
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. # Modified from ESPnet(https://github.com/espnet/espnet)
  17. """Unility functions for Transformer."""
  18. import queue
  19. import random
  20. from typing import List
  21. import numpy as np
  22. import torch
  23. IGNORE_ID = -1
  24. def pad_list(xs: List[torch.Tensor], pad_value: int):
  25. """Perform padding for the list of tensors.
  26. Args:
  27. xs (List): List of Tensors [(T_1, `*`), (T_2, `*`), ..., (T_B, `*`)].
  28. pad_value (float): Value for padding.
  29. Returns:
  30. Tensor: Padded tensor (B, Tmax, `*`).
  31. Examples:
  32. >>> x = [torch.ones(4), torch.ones(2), torch.ones(1)]
  33. >>> x
  34. [tensor([1., 1., 1., 1.]), tensor([1., 1.]), tensor([1.])]
  35. >>> pad_list(x, 0)
  36. tensor([[1., 1., 1., 1.],
  37. [1., 1., 0., 0.],
  38. [1., 0., 0., 0.]])
  39. """
  40. max_len = max([len(item) for item in xs])
  41. batchs = len(xs)
  42. ndim = xs[0].ndim
  43. if ndim == 1:
  44. pad_res = torch.zeros(batchs,
  45. max_len,
  46. dtype=xs[0].dtype,
  47. device=xs[0].device)
  48. elif ndim == 2:
  49. pad_res = torch.zeros(batchs,
  50. max_len,
  51. xs[0].shape[1],
  52. dtype=xs[0].dtype,
  53. device=xs[0].device)
  54. elif ndim == 3:
  55. pad_res = torch.zeros(batchs,
  56. max_len,
  57. xs[0].shape[1],
  58. xs[0].shape[2],
  59. dtype=xs[0].dtype,
  60. device=xs[0].device)
  61. else:
  62. raise ValueError(f"Unsupported ndim: {ndim}")
  63. pad_res.fill_(pad_value)
  64. for i in range(batchs):
  65. pad_res[i, :len(xs[i])] = xs[i]
  66. return pad_res
  67. def th_accuracy(pad_outputs: torch.Tensor, pad_targets: torch.Tensor,
  68. ignore_label: int) -> torch.Tensor:
  69. """Calculate accuracy.
  70. Args:
  71. pad_outputs (Tensor): Prediction tensors (B * Lmax, D).
  72. pad_targets (LongTensor): Target label tensors (B, Lmax).
  73. ignore_label (int): Ignore label id.
  74. Returns:
  75. torch.Tensor: Accuracy value (0.0 - 1.0).
  76. """
  77. pad_pred = pad_outputs.view(pad_targets.size(0), pad_targets.size(1),
  78. pad_outputs.size(1)).argmax(2)
  79. mask = pad_targets != ignore_label
  80. numerator = torch.sum(
  81. pad_pred.masked_select(mask) == pad_targets.masked_select(mask))
  82. denominator = torch.sum(mask)
  83. return (numerator / denominator).detach()
  84. def get_padding(kernel_size, dilation=1):
  85. return int((kernel_size * dilation - dilation) / 2)
  86. def init_weights(m, mean=0.0, std=0.01):
  87. classname = m.__class__.__name__
  88. if classname.find("Conv") != -1:
  89. m.weight.data.normal_(mean, std)
  90. # Repetition Aware Sampling in VALL-E 2
  91. def ras_sampling(weighted_scores, decoded_tokens, sampling, top_p=0.8, top_k=25, win_size=10, tau_r=0.1):
  92. top_ids = nucleus_sampling(weighted_scores, top_p=top_p, top_k=top_k)
  93. rep_num = (torch.tensor(decoded_tokens[-win_size:]).to(weighted_scores.device) == top_ids).sum().item()
  94. if rep_num >= win_size * tau_r:
  95. top_ids = random_sampling(weighted_scores, decoded_tokens, sampling)
  96. return top_ids
  97. def nucleus_sampling(weighted_scores, top_p=0.8, top_k=25):
  98. prob, indices = [], []
  99. cum_prob = 0.0
  100. sorted_value, sorted_idx = weighted_scores.softmax(dim=0).sort(descending=True, stable=True)
  101. for i in range(len(sorted_idx)):
  102. # sampling both top-p and numbers.
  103. if cum_prob < top_p and len(prob) < top_k:
  104. cum_prob += sorted_value[i]
  105. prob.append(sorted_value[i])
  106. indices.append(sorted_idx[i])
  107. else:
  108. break
  109. prob = torch.tensor(prob).to(weighted_scores)
  110. indices = torch.tensor(indices, dtype=torch.long).to(weighted_scores.device)
  111. top_ids = indices[prob.multinomial(1, replacement=True)]
  112. return top_ids
  113. def random_sampling(weighted_scores, decoded_tokens, sampling):
  114. top_ids = weighted_scores.softmax(dim=0).multinomial(1, replacement=True)
  115. return top_ids
  116. def fade_in_out(fade_in_mel, fade_out_mel, window):
  117. device = fade_in_mel.device
  118. fade_in_mel, fade_out_mel = fade_in_mel.cpu(), fade_out_mel.cpu()
  119. mel_overlap_len = int(window.shape[0] / 2)
  120. if fade_in_mel.device == torch.device('cpu'):
  121. fade_in_mel = fade_in_mel.clone()
  122. fade_in_mel[..., :mel_overlap_len] = fade_in_mel[..., :mel_overlap_len] * window[:mel_overlap_len] + \
  123. fade_out_mel[..., -mel_overlap_len:] * window[mel_overlap_len:]
  124. return fade_in_mel.to(device)
  125. def set_all_random_seed(seed):
  126. random.seed(seed)
  127. np.random.seed(seed)
  128. torch.manual_seed(seed)
  129. torch.cuda.manual_seed_all(seed)
  130. def mask_to_bias(mask: torch.Tensor, dtype: torch.dtype) -> torch.Tensor:
  131. assert mask.dtype == torch.bool
  132. assert dtype in [torch.float32, torch.bfloat16, torch.float16]
  133. mask = mask.to(dtype)
  134. # attention mask bias
  135. # NOTE(Mddct): torch.finfo jit issues
  136. # chunk_masks = (1.0 - chunk_masks) * torch.finfo(dtype).min
  137. mask = (1.0 - mask) * -1.0e+10
  138. return mask
  139. class TrtContextWrapper:
  140. def __init__(self, trt_engine, trt_concurrent=1):
  141. self.trt_context_pool = queue.Queue()
  142. self.trt_engine = trt_engine
  143. for _ in range(trt_concurrent):
  144. trt_context = trt_engine.create_execution_context()
  145. assert trt_context is not None, 'failed to create trt context, maybe not enough CUDA memory, try reduce current trt concurrent {}'.format(trt_concurrent)
  146. self.trt_context_pool.put(trt_context)
  147. assert self.trt_context_pool.empty() is False, 'no avaialbe estimator context'
  148. def acquire_estimator(self):
  149. return self.trt_context_pool.get(), self.trt_engine
  150. def release_estimator(self, context):
  151. self.trt_context_pool.put(context)