common.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  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. instruct_list = ["You are a helpful assistant. 请用广东话表达。<|endofprompt|>",
  25. "You are a helpful assistant. 请用东北话表达。<|endofprompt|>",
  26. "You are a helpful assistant. 请用甘肃话表达。<|endofprompt|>",
  27. "You are a helpful assistant. 请用贵州话表达。<|endofprompt|>",
  28. "You are a helpful assistant. 请用河南话表达。<|endofprompt|>",
  29. "You are a helpful assistant. 请用湖北话表达。<|endofprompt|>",
  30. "You are a helpful assistant. 请用湖南话表达。<|endofprompt|>",
  31. "You are a helpful assistant. 请用江西话表达。<|endofprompt|>",
  32. "You are a helpful assistant. 请用闽南话表达。<|endofprompt|>",
  33. "You are a helpful assistant. 请用宁夏话表达。<|endofprompt|>",
  34. "You are a helpful assistant. 请用山西话表达。<|endofprompt|>",
  35. "You are a helpful assistant. 请用陕西话表达。<|endofprompt|>",
  36. "You are a helpful assistant. 请用山东话表达。<|endofprompt|>",
  37. "You are a helpful assistant. 请用上海话表达。<|endofprompt|>",
  38. "You are a helpful assistant. 请用四川话表达。<|endofprompt|>",
  39. "You are a helpful assistant. 请用天津话表达。<|endofprompt|>",
  40. "You are a helpful assistant. 请用云南话表达。<|endofprompt|>",
  41. "You are a helpful assistant. Please say a sentence as loudly as possible.<|endofprompt|>",
  42. "You are a helpful assistant. Please say a sentence in a very soft voice.<|endofprompt|>",
  43. "You are a helpful assistant. 请用尽可能慢地语速说一句话。<|endofprompt|>",
  44. "You are a helpful assistant. 请用尽可能快地语速说一句话。<|endofprompt|>",
  45. "You are a helpful assistant. 请非常开心地说一句话。<|endofprompt|>",
  46. "You are a helpful assistant. 请非常伤心地说一句话。<|endofprompt|>",
  47. "You are a helpful assistant. 请非常生气地说一句话。<|endofprompt|>",
  48. "You are a helpful assistant. 我想体验一下小猪佩奇风格,可以吗?<|endofprompt|>",
  49. "You are a helpful assistant. 你可以尝试用机器人的方式解答吗?<|endofprompt|>"]
  50. def pad_list(xs: List[torch.Tensor], pad_value: int):
  51. """Perform padding for the list of tensors.
  52. Args:
  53. xs (List): List of Tensors [(T_1, `*`), (T_2, `*`), ..., (T_B, `*`)].
  54. pad_value (float): Value for padding.
  55. Returns:
  56. Tensor: Padded tensor (B, Tmax, `*`).
  57. Examples:
  58. >>> x = [torch.ones(4), torch.ones(2), torch.ones(1)]
  59. >>> x
  60. [tensor([1., 1., 1., 1.]), tensor([1., 1.]), tensor([1.])]
  61. >>> pad_list(x, 0)
  62. tensor([[1., 1., 1., 1.],
  63. [1., 1., 0., 0.],
  64. [1., 0., 0., 0.]])
  65. """
  66. max_len = max([len(item) for item in xs])
  67. batchs = len(xs)
  68. ndim = xs[0].ndim
  69. if ndim == 1:
  70. pad_res = torch.zeros(batchs,
  71. max_len,
  72. dtype=xs[0].dtype,
  73. device=xs[0].device)
  74. elif ndim == 2:
  75. pad_res = torch.zeros(batchs,
  76. max_len,
  77. xs[0].shape[1],
  78. dtype=xs[0].dtype,
  79. device=xs[0].device)
  80. elif ndim == 3:
  81. pad_res = torch.zeros(batchs,
  82. max_len,
  83. xs[0].shape[1],
  84. xs[0].shape[2],
  85. dtype=xs[0].dtype,
  86. device=xs[0].device)
  87. else:
  88. raise ValueError(f"Unsupported ndim: {ndim}")
  89. pad_res.fill_(pad_value)
  90. for i in range(batchs):
  91. pad_res[i, :len(xs[i])] = xs[i]
  92. return pad_res
  93. def th_accuracy(pad_outputs: torch.Tensor, pad_targets: torch.Tensor,
  94. ignore_label: int) -> torch.Tensor:
  95. """Calculate accuracy.
  96. Args:
  97. pad_outputs (Tensor): Prediction tensors (B * Lmax, D).
  98. pad_targets (LongTensor): Target label tensors (B, Lmax).
  99. ignore_label (int): Ignore label id.
  100. Returns:
  101. torch.Tensor: Accuracy value (0.0 - 1.0).
  102. """
  103. pad_pred = pad_outputs.view(pad_targets.size(0), pad_targets.size(1),
  104. pad_outputs.size(1)).argmax(2)
  105. mask = pad_targets != ignore_label
  106. numerator = torch.sum(
  107. pad_pred.masked_select(mask) == pad_targets.masked_select(mask))
  108. denominator = torch.sum(mask)
  109. return (numerator / denominator).detach()
  110. def get_padding(kernel_size, dilation=1):
  111. return int((kernel_size * dilation - dilation) / 2)
  112. def init_weights(m, mean=0.0, std=0.01):
  113. classname = m.__class__.__name__
  114. if classname.find("Conv") != -1:
  115. m.weight.data.normal_(mean, std)
  116. # Repetition Aware Sampling in VALL-E 2
  117. def ras_sampling(weighted_scores, decoded_tokens, sampling, top_p=0.8, top_k=25, win_size=10, tau_r=0.1):
  118. top_ids = nucleus_sampling(weighted_scores, top_p=top_p, top_k=top_k)
  119. rep_num = (torch.tensor(decoded_tokens[-win_size:]).to(weighted_scores.device) == top_ids).sum().item()
  120. if rep_num >= win_size * tau_r:
  121. top_ids = random_sampling(weighted_scores, decoded_tokens, sampling)
  122. return top_ids
  123. def nucleus_sampling(weighted_scores, top_p=0.8, top_k=25):
  124. prob, indices = [], []
  125. cum_prob = 0.0
  126. sorted_value, sorted_idx = weighted_scores.softmax(dim=0).sort(descending=True, stable=True)
  127. for i in range(len(sorted_idx)):
  128. # sampling both top-p and numbers.
  129. if cum_prob < top_p and len(prob) < top_k:
  130. cum_prob += sorted_value[i]
  131. prob.append(sorted_value[i])
  132. indices.append(sorted_idx[i])
  133. else:
  134. break
  135. prob = torch.tensor(prob).to(weighted_scores)
  136. indices = torch.tensor(indices, dtype=torch.long).to(weighted_scores.device)
  137. top_ids = indices[prob.multinomial(1, replacement=True)].item()
  138. return top_ids
  139. def random_sampling(weighted_scores, decoded_tokens, sampling):
  140. top_ids = weighted_scores.softmax(dim=0).multinomial(1, replacement=True).item()
  141. return top_ids
  142. def fade_in_out(fade_in_mel, fade_out_mel, window):
  143. device = fade_in_mel.device
  144. fade_in_mel, fade_out_mel = fade_in_mel.cpu(), fade_out_mel.cpu()
  145. mel_overlap_len = int(window.shape[0] / 2)
  146. if fade_in_mel.device == torch.device('cpu'):
  147. fade_in_mel = fade_in_mel.clone()
  148. fade_in_mel[..., :mel_overlap_len] = fade_in_mel[..., :mel_overlap_len] * window[:mel_overlap_len] + \
  149. fade_out_mel[..., -mel_overlap_len:] * window[mel_overlap_len:]
  150. return fade_in_mel.to(device)
  151. def set_all_random_seed(seed):
  152. random.seed(seed)
  153. np.random.seed(seed)
  154. torch.manual_seed(seed)
  155. torch.cuda.manual_seed_all(seed)
  156. def mask_to_bias(mask: torch.Tensor, dtype: torch.dtype) -> torch.Tensor:
  157. assert mask.dtype == torch.bool
  158. assert dtype in [torch.float32, torch.bfloat16, torch.float16]
  159. mask = mask.to(dtype)
  160. # attention mask bias
  161. # NOTE(Mddct): torch.finfo jit issues
  162. # chunk_masks = (1.0 - chunk_masks) * torch.finfo(dtype).min
  163. mask = (1.0 - mask) * -1.0e+10
  164. return mask
  165. class TrtContextWrapper:
  166. def __init__(self, trt_engine, trt_concurrent=1, device='cuda:0'):
  167. self.trt_context_pool = queue.Queue(maxsize=trt_concurrent)
  168. self.trt_engine = trt_engine
  169. for _ in range(trt_concurrent):
  170. trt_context = trt_engine.create_execution_context()
  171. trt_stream = torch.cuda.stream(torch.cuda.Stream(device))
  172. assert trt_context is not None, 'failed to create trt context, maybe not enough CUDA memory, try reduce current trt concurrent {}'.format(trt_concurrent)
  173. self.trt_context_pool.put([trt_context, trt_stream])
  174. assert self.trt_context_pool.empty() is False, 'no avaialbe estimator context'
  175. def acquire_estimator(self):
  176. return self.trt_context_pool.get(), self.trt_engine
  177. def release_estimator(self, context, stream):
  178. self.trt_context_pool.put([context, stream])