cif.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. import torch
  4. from torch import nn
  5. def sequence_mask(lengths, maxlen=None, dtype=torch.float32, device=None):
  6. if maxlen is None:
  7. maxlen = lengths.max()
  8. row_vector = torch.arange(0, maxlen, 1).to(lengths.device)
  9. matrix = torch.unsqueeze(lengths, dim=-1)
  10. mask = row_vector < matrix
  11. mask = mask.detach()
  12. return mask.type(dtype).to(device) if device is not None else mask.type(dtype)
  13. def sequence_mask_scripts(lengths, maxlen:int):
  14. row_vector = torch.arange(0, maxlen, 1).type(lengths.dtype).to(lengths.device)
  15. matrix = torch.unsqueeze(lengths, dim=-1)
  16. mask = row_vector < matrix
  17. return mask.type(torch.float32).to(lengths.device)
  18. class CifPredictorV2(nn.Module):
  19. def __init__(self, model):
  20. super().__init__()
  21. self.pad = model.pad
  22. self.cif_conv1d = model.cif_conv1d
  23. self.cif_output = model.cif_output
  24. self.threshold = model.threshold
  25. self.smooth_factor = model.smooth_factor
  26. self.noise_threshold = model.noise_threshold
  27. self.tail_threshold = model.tail_threshold
  28. def forward(self, hidden: torch.Tensor,
  29. mask: torch.Tensor,
  30. ):
  31. h = hidden
  32. context = h.transpose(1, 2)
  33. queries = self.pad(context)
  34. output = torch.relu(self.cif_conv1d(queries))
  35. output = output.transpose(1, 2)
  36. output = self.cif_output(output)
  37. alphas = torch.sigmoid(output)
  38. alphas = torch.nn.functional.relu(alphas * self.smooth_factor - self.noise_threshold)
  39. mask = mask.transpose(-1, -2).float()
  40. alphas = alphas * mask
  41. alphas = alphas.squeeze(-1)
  42. token_num = alphas.sum(-1)
  43. mask = mask.squeeze(-1)
  44. hidden, alphas, token_num = self.tail_process_fn(hidden, alphas, mask=mask)
  45. acoustic_embeds, cif_peak = cif(hidden, alphas, self.threshold)
  46. return acoustic_embeds, token_num, alphas, cif_peak
  47. def tail_process_fn(self, hidden, alphas, token_num=None, mask=None):
  48. b, t, d = hidden.size()
  49. tail_threshold = self.tail_threshold
  50. zeros_t = torch.zeros((b, 1), dtype=torch.float32, device=alphas.device)
  51. ones_t = torch.ones_like(zeros_t)
  52. mask_1 = torch.cat([mask, zeros_t], dim=1)
  53. mask_2 = torch.cat([ones_t, mask], dim=1)
  54. mask = mask_2 - mask_1
  55. tail_threshold = mask * tail_threshold
  56. alphas = torch.cat([alphas, zeros_t], dim=1)
  57. alphas = torch.add(alphas, tail_threshold)
  58. zeros = torch.zeros((b, 1, d), dtype=hidden.dtype).to(hidden.device)
  59. hidden = torch.cat([hidden, zeros], dim=1)
  60. token_num = alphas.sum(dim=-1)
  61. token_num_floor = torch.floor(token_num)
  62. return hidden, alphas, token_num_floor
  63. # @torch.jit.script
  64. # def cif(hidden, alphas, threshold: float):
  65. # batch_size, len_time, hidden_size = hidden.size()
  66. # threshold = torch.tensor([threshold], dtype=alphas.dtype).to(alphas.device)
  67. #
  68. # # loop varss
  69. # integrate = torch.zeros([batch_size], device=hidden.device)
  70. # frame = torch.zeros([batch_size, hidden_size], device=hidden.device)
  71. # # intermediate vars along time
  72. # list_fires = []
  73. # list_frames = []
  74. #
  75. # for t in range(len_time):
  76. # alpha = alphas[:, t]
  77. # distribution_completion = torch.ones([batch_size], device=hidden.device) - integrate
  78. #
  79. # integrate += alpha
  80. # list_fires.append(integrate)
  81. #
  82. # fire_place = integrate >= threshold
  83. # integrate = torch.where(fire_place,
  84. # integrate - torch.ones([batch_size], device=hidden.device),
  85. # integrate)
  86. # cur = torch.where(fire_place,
  87. # distribution_completion,
  88. # alpha)
  89. # remainds = alpha - cur
  90. #
  91. # frame += cur[:, None] * hidden[:, t, :]
  92. # list_frames.append(frame)
  93. # frame = torch.where(fire_place[:, None].repeat(1, hidden_size),
  94. # remainds[:, None] * hidden[:, t, :],
  95. # frame)
  96. #
  97. # fires = torch.stack(list_fires, 1)
  98. # frames = torch.stack(list_frames, 1)
  99. # list_ls = []
  100. # len_labels = torch.floor(alphas.sum(-1)).int()
  101. # max_label_len = len_labels.max()
  102. # for b in range(batch_size):
  103. # fire = fires[b, :]
  104. # l = torch.index_select(frames[b, :, :], 0, torch.nonzero(fire >= threshold).squeeze())
  105. # pad_l = torch.zeros([int(max_label_len - l.size(0)), int(hidden_size)], device=hidden.device)
  106. # list_ls.append(torch.cat([l, pad_l], 0))
  107. # return torch.stack(list_ls, 0), fires
  108. @torch.jit.script
  109. def cif(hidden, alphas, threshold: float):
  110. batch_size, len_time, hidden_size = hidden.size()
  111. threshold = torch.tensor([threshold], dtype=alphas.dtype).to(alphas.device)
  112. # loop varss
  113. integrate = torch.zeros([batch_size], dtype=alphas.dtype, device=hidden.device)
  114. frame = torch.zeros([batch_size, hidden_size], dtype=hidden.dtype, device=hidden.device)
  115. # intermediate vars along time
  116. list_fires = []
  117. list_frames = []
  118. for t in range(len_time):
  119. alpha = alphas[:, t]
  120. distribution_completion = torch.ones([batch_size], dtype=alphas.dtype, device=hidden.device) - integrate
  121. integrate += alpha
  122. list_fires.append(integrate)
  123. fire_place = integrate >= threshold
  124. integrate = torch.where(fire_place,
  125. integrate - torch.ones([batch_size], dtype=alphas.dtype, device=hidden.device),
  126. integrate)
  127. cur = torch.where(fire_place,
  128. distribution_completion,
  129. alpha)
  130. remainds = alpha - cur
  131. frame += cur[:, None] * hidden[:, t, :]
  132. list_frames.append(frame)
  133. frame = torch.where(fire_place[:, None].repeat(1, hidden_size),
  134. remainds[:, None] * hidden[:, t, :],
  135. frame)
  136. fires = torch.stack(list_fires, 1)
  137. frames = torch.stack(list_frames, 1)
  138. fire_idxs = fires >= threshold
  139. frame_fires = torch.zeros_like(hidden)
  140. max_label_len = frames[0, fire_idxs[0]].size(0)
  141. for b in range(batch_size):
  142. frame_fire = frames[b, fire_idxs[b]]
  143. frame_len = frame_fire.size(0)
  144. frame_fires[b, :frame_len, :] = frame_fire
  145. if frame_len >= max_label_len:
  146. max_label_len = frame_len
  147. frame_fires = frame_fires[:, :max_label_len, :]
  148. return frame_fires, fires
  149. class CifPredictorV3(nn.Module):
  150. def __init__(self, model):
  151. super().__init__()
  152. self.pad = model.pad
  153. self.cif_conv1d = model.cif_conv1d
  154. self.cif_output = model.cif_output
  155. self.threshold = model.threshold
  156. self.smooth_factor = model.smooth_factor
  157. self.noise_threshold = model.noise_threshold
  158. self.tail_threshold = model.tail_threshold
  159. self.upsample_times = model.upsample_times
  160. self.upsample_cnn = model.upsample_cnn
  161. self.blstm = model.blstm
  162. self.cif_output2 = model.cif_output2
  163. self.smooth_factor2 = model.smooth_factor2
  164. self.noise_threshold2 = model.noise_threshold2
  165. def forward(self, hidden: torch.Tensor,
  166. mask: torch.Tensor,
  167. ):
  168. h = hidden
  169. context = h.transpose(1, 2)
  170. queries = self.pad(context)
  171. output = torch.relu(self.cif_conv1d(queries))
  172. output = output.transpose(1, 2)
  173. output = self.cif_output(output)
  174. alphas = torch.sigmoid(output)
  175. alphas = torch.nn.functional.relu(alphas * self.smooth_factor - self.noise_threshold)
  176. mask = mask.transpose(-1, -2).float()
  177. alphas = alphas * mask
  178. alphas = alphas.squeeze(-1)
  179. token_num = alphas.sum(-1)
  180. mask = mask.squeeze(-1)
  181. hidden, alphas, token_num = self.tail_process_fn(hidden, alphas, mask=mask)
  182. acoustic_embeds, cif_peak = cif(hidden, alphas, self.threshold)
  183. return acoustic_embeds, token_num, alphas, cif_peak
  184. def get_upsample_timestmap(self, hidden, mask=None, token_num=None):
  185. h = hidden
  186. b = hidden.shape[0]
  187. context = h.transpose(1, 2)
  188. # generate alphas2
  189. _output = context
  190. output2 = self.upsample_cnn(_output)
  191. output2 = output2.transpose(1, 2)
  192. output2, (_, _) = self.blstm(output2)
  193. alphas2 = torch.sigmoid(self.cif_output2(output2))
  194. alphas2 = torch.nn.functional.relu(alphas2 * self.smooth_factor2 - self.noise_threshold2)
  195. mask = mask.repeat(1, self.upsample_times, 1).transpose(-1, -2).reshape(alphas2.shape[0], -1)
  196. mask = mask.unsqueeze(-1)
  197. alphas2 = alphas2 * mask
  198. alphas2 = alphas2.squeeze(-1)
  199. _token_num = alphas2.sum(-1)
  200. alphas2 *= (token_num / _token_num)[:, None].repeat(1, alphas2.size(1))
  201. # upsampled alphas and cif_peak
  202. us_alphas = alphas2
  203. us_cif_peak = cif_wo_hidden(us_alphas, self.threshold - 1e-4)
  204. return us_alphas, us_cif_peak
  205. def tail_process_fn(self, hidden, alphas, token_num=None, mask=None):
  206. b, t, d = hidden.size()
  207. tail_threshold = self.tail_threshold
  208. zeros_t = torch.zeros((b, 1), dtype=torch.float32, device=alphas.device)
  209. ones_t = torch.ones_like(zeros_t)
  210. mask_1 = torch.cat([mask, zeros_t], dim=1)
  211. mask_2 = torch.cat([ones_t, mask], dim=1)
  212. mask = mask_2 - mask_1
  213. tail_threshold = mask * tail_threshold
  214. alphas = torch.cat([alphas, zeros_t], dim=1)
  215. alphas = torch.add(alphas, tail_threshold)
  216. zeros = torch.zeros((b, 1, d), dtype=hidden.dtype).to(hidden.device)
  217. hidden = torch.cat([hidden, zeros], dim=1)
  218. token_num = alphas.sum(dim=-1)
  219. token_num_floor = torch.floor(token_num)
  220. return hidden, alphas, token_num_floor
  221. @torch.jit.script
  222. def cif_wo_hidden(alphas, threshold: float):
  223. batch_size, len_time = alphas.size()
  224. # loop varss
  225. integrate = torch.zeros([batch_size], dtype=alphas.dtype, device=alphas.device)
  226. # intermediate vars along time
  227. list_fires = []
  228. for t in range(len_time):
  229. alpha = alphas[:, t]
  230. integrate += alpha
  231. list_fires.append(integrate)
  232. fire_place = integrate >= threshold
  233. integrate = torch.where(fire_place,
  234. integrate - torch.ones([batch_size], device=alphas.device),
  235. integrate)
  236. fires = torch.stack(list_fires, 1)
  237. return fires