cif.py 9.9 KB

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