cif.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. import torch
  4. from torch import nn
  5. import logging
  6. import numpy as np
  7. def sequence_mask(lengths, maxlen=None, dtype=torch.float32, device=None):
  8. if maxlen is None:
  9. maxlen = lengths.max()
  10. row_vector = torch.arange(0, maxlen, 1).to(lengths.device)
  11. matrix = torch.unsqueeze(lengths, dim=-1)
  12. mask = row_vector < matrix
  13. mask = mask.detach()
  14. return mask.type(dtype).to(device) if device is not None else mask.type(dtype)
  15. def sequence_mask_scripts(lengths, maxlen:int):
  16. row_vector = torch.arange(0, maxlen, 1).type(lengths.dtype).to(lengths.device)
  17. matrix = torch.unsqueeze(lengths, dim=-1)
  18. mask = row_vector < matrix
  19. return mask.type(torch.float32).to(lengths.device)
  20. class CifPredictorV2(nn.Module):
  21. def __init__(self, model):
  22. super().__init__()
  23. self.pad = model.pad
  24. self.cif_conv1d = model.cif_conv1d
  25. self.cif_output = model.cif_output
  26. self.threshold = model.threshold
  27. self.smooth_factor = model.smooth_factor
  28. self.noise_threshold = model.noise_threshold
  29. self.tail_threshold = model.tail_threshold
  30. def forward(self, hidden: torch.Tensor,
  31. mask: torch.Tensor,
  32. ):
  33. h = hidden
  34. context = h.transpose(1, 2)
  35. queries = self.pad(context)
  36. output = torch.relu(self.cif_conv1d(queries))
  37. output = output.transpose(1, 2)
  38. output = self.cif_output(output)
  39. alphas = torch.sigmoid(output)
  40. alphas = torch.nn.functional.relu(alphas * self.smooth_factor - self.noise_threshold)
  41. mask = mask.transpose(-1, -2).float()
  42. alphas = alphas * mask
  43. alphas = alphas.squeeze(-1)
  44. token_num = alphas.sum(-1)
  45. mask = mask.squeeze(-1)
  46. hidden, alphas, token_num = self.tail_process_fn(hidden, alphas, mask=mask)
  47. acoustic_embeds, cif_peak = cif(hidden, alphas, self.threshold)
  48. return acoustic_embeds, token_num, alphas, cif_peak
  49. def tail_process_fn(self, hidden, alphas, token_num=None, mask=None):
  50. b, t, d = hidden.size()
  51. tail_threshold = self.tail_threshold
  52. zeros_t = torch.zeros((b, 1), dtype=torch.float32, device=alphas.device)
  53. ones_t = torch.ones_like(zeros_t)
  54. mask_1 = torch.cat([mask, zeros_t], dim=1)
  55. mask_2 = torch.cat([ones_t, mask], dim=1)
  56. mask = mask_2 - mask_1
  57. tail_threshold = mask * tail_threshold
  58. alphas = torch.cat([alphas, zeros_t], dim=1)
  59. alphas = torch.add(alphas, tail_threshold)
  60. zeros = torch.zeros((b, 1, d), dtype=hidden.dtype).to(hidden.device)
  61. hidden = torch.cat([hidden, zeros], dim=1)
  62. token_num = alphas.sum(dim=-1)
  63. token_num_floor = torch.floor(token_num)
  64. return hidden, alphas, token_num_floor
  65. # @torch.jit.script
  66. # def cif(hidden, alphas, threshold: float):
  67. # batch_size, len_time, hidden_size = hidden.size()
  68. # threshold = torch.tensor([threshold], dtype=alphas.dtype).to(alphas.device)
  69. #
  70. # # loop varss
  71. # integrate = torch.zeros([batch_size], device=hidden.device)
  72. # frame = torch.zeros([batch_size, hidden_size], device=hidden.device)
  73. # # intermediate vars along time
  74. # list_fires = []
  75. # list_frames = []
  76. #
  77. # for t in range(len_time):
  78. # alpha = alphas[:, t]
  79. # distribution_completion = torch.ones([batch_size], device=hidden.device) - integrate
  80. #
  81. # integrate += alpha
  82. # list_fires.append(integrate)
  83. #
  84. # fire_place = integrate >= threshold
  85. # integrate = torch.where(fire_place,
  86. # integrate - torch.ones([batch_size], device=hidden.device),
  87. # integrate)
  88. # cur = torch.where(fire_place,
  89. # distribution_completion,
  90. # alpha)
  91. # remainds = alpha - cur
  92. #
  93. # frame += cur[:, None] * hidden[:, t, :]
  94. # list_frames.append(frame)
  95. # frame = torch.where(fire_place[:, None].repeat(1, hidden_size),
  96. # remainds[:, None] * hidden[:, t, :],
  97. # frame)
  98. #
  99. # fires = torch.stack(list_fires, 1)
  100. # frames = torch.stack(list_frames, 1)
  101. # list_ls = []
  102. # len_labels = torch.floor(alphas.sum(-1)).int()
  103. # max_label_len = len_labels.max()
  104. # for b in range(batch_size):
  105. # fire = fires[b, :]
  106. # l = torch.index_select(frames[b, :, :], 0, torch.nonzero(fire >= threshold).squeeze())
  107. # pad_l = torch.zeros([int(max_label_len - l.size(0)), int(hidden_size)], device=hidden.device)
  108. # list_ls.append(torch.cat([l, pad_l], 0))
  109. # return torch.stack(list_ls, 0), fires
  110. @torch.jit.script
  111. def cif(hidden, alphas, threshold: float):
  112. batch_size, len_time, hidden_size = hidden.size()
  113. threshold = torch.tensor([threshold], dtype=alphas.dtype).to(alphas.device)
  114. # loop varss
  115. integrate = torch.zeros([batch_size], dtype=alphas.dtype, device=hidden.device)
  116. frame = torch.zeros([batch_size, hidden_size], dtype=hidden.dtype, device=hidden.device)
  117. # intermediate vars along time
  118. list_fires = []
  119. list_frames = []
  120. for t in range(len_time):
  121. alpha = alphas[:, t]
  122. distribution_completion = torch.ones([batch_size], dtype=alphas.dtype, device=hidden.device) - integrate
  123. integrate += alpha
  124. list_fires.append(integrate)
  125. fire_place = integrate >= threshold
  126. integrate = torch.where(fire_place,
  127. integrate - torch.ones([batch_size], dtype=alphas.dtype, device=hidden.device),
  128. integrate)
  129. cur = torch.where(fire_place,
  130. distribution_completion,
  131. alpha)
  132. remainds = alpha - cur
  133. frame += cur[:, None] * hidden[:, t, :]
  134. list_frames.append(frame)
  135. frame = torch.where(fire_place[:, None].repeat(1, hidden_size),
  136. remainds[:, None] * hidden[:, t, :],
  137. frame)
  138. fires = torch.stack(list_fires, 1)
  139. frames = torch.stack(list_frames, 1)
  140. fire_idxs = fires >= threshold
  141. frame_fires = torch.zeros_like(hidden)
  142. max_label_len = frames[0, fire_idxs[0]].size(0)
  143. for b in range(batch_size):
  144. frame_fire = frames[b, fire_idxs[b]]
  145. frame_len = frame_fire.size(0)
  146. frame_fires[b, :frame_len, :] = frame_fire
  147. if frame_len >= max_label_len:
  148. max_label_len = frame_len
  149. frame_fires = frame_fires[:, :max_label_len, :]
  150. return frame_fires, fires