cif.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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. 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, tail_threshold], dim=1)
  57. zeros = torch.zeros((b, 1, d), dtype=hidden.dtype).to(hidden.device)
  58. hidden = torch.cat([hidden, zeros], dim=1)
  59. token_num = alphas.sum(dim=-1)
  60. token_num_floor = torch.floor(token_num)
  61. return hidden, alphas, token_num_floor
  62. # @torch.jit.script
  63. # def cif(hidden, alphas, threshold: float):
  64. # batch_size, len_time, hidden_size = hidden.size()
  65. # threshold = torch.tensor([threshold], dtype=alphas.dtype).to(alphas.device)
  66. #
  67. # # loop varss
  68. # integrate = torch.zeros([batch_size], device=hidden.device)
  69. # frame = torch.zeros([batch_size, hidden_size], device=hidden.device)
  70. # # intermediate vars along time
  71. # list_fires = []
  72. # list_frames = []
  73. #
  74. # for t in range(len_time):
  75. # alpha = alphas[:, t]
  76. # distribution_completion = torch.ones([batch_size], device=hidden.device) - integrate
  77. #
  78. # integrate += alpha
  79. # list_fires.append(integrate)
  80. #
  81. # fire_place = integrate >= threshold
  82. # integrate = torch.where(fire_place,
  83. # integrate - torch.ones([batch_size], device=hidden.device),
  84. # integrate)
  85. # cur = torch.where(fire_place,
  86. # distribution_completion,
  87. # alpha)
  88. # remainds = alpha - cur
  89. #
  90. # frame += cur[:, None] * hidden[:, t, :]
  91. # list_frames.append(frame)
  92. # frame = torch.where(fire_place[:, None].repeat(1, hidden_size),
  93. # remainds[:, None] * hidden[:, t, :],
  94. # frame)
  95. #
  96. # fires = torch.stack(list_fires, 1)
  97. # frames = torch.stack(list_frames, 1)
  98. # list_ls = []
  99. # len_labels = torch.floor(alphas.sum(-1)).int()
  100. # max_label_len = len_labels.max()
  101. # for b in range(batch_size):
  102. # fire = fires[b, :]
  103. # l = torch.index_select(frames[b, :, :], 0, torch.nonzero(fire >= threshold).squeeze())
  104. # pad_l = torch.zeros([int(max_label_len - l.size(0)), int(hidden_size)], device=hidden.device)
  105. # list_ls.append(torch.cat([l, pad_l], 0))
  106. # return torch.stack(list_ls, 0), fires
  107. @torch.jit.script
  108. def cif(hidden, alphas, threshold: float):
  109. batch_size, len_time, hidden_size = hidden.size()
  110. threshold = torch.tensor([threshold], dtype=alphas.dtype).to(alphas.device)
  111. # loop varss
  112. integrate = torch.zeros([batch_size], dtype=alphas.dtype, device=hidden.device)
  113. frame = torch.zeros([batch_size, hidden_size], dtype=hidden.dtype, device=hidden.device)
  114. # intermediate vars along time
  115. list_fires = []
  116. list_frames = []
  117. for t in range(len_time):
  118. alpha = alphas[:, t]
  119. distribution_completion = torch.ones([batch_size], dtype=alphas.dtype, device=hidden.device) - integrate
  120. integrate += alpha
  121. list_fires.append(integrate)
  122. fire_place = integrate >= threshold
  123. integrate = torch.where(fire_place,
  124. integrate - torch.ones([batch_size], dtype=alphas.dtype, device=hidden.device),
  125. integrate)
  126. cur = torch.where(fire_place,
  127. distribution_completion,
  128. alpha)
  129. remainds = alpha - cur
  130. frame += cur[:, None] * hidden[:, t, :]
  131. list_frames.append(frame)
  132. frame = torch.where(fire_place[:, None].repeat(1, hidden_size),
  133. remainds[:, None] * hidden[:, t, :],
  134. frame)
  135. fires = torch.stack(list_fires, 1)
  136. frames = torch.stack(list_frames, 1)
  137. fire_idxs = fires >= threshold
  138. frame_fires = torch.zeros_like(hidden)
  139. max_label_len = frames[0, fire_idxs[0]].size(0)
  140. for b in range(batch_size):
  141. frame_fire = frames[b, fire_idxs[b]]
  142. frame_len = frame_fire.size(0)
  143. frame_fires[b, :frame_len, :] = frame_fire
  144. if frame_len >= max_label_len:
  145. max_label_len = frame_len
  146. frame_fires = frame_fires[:, :max_label_len, :]
  147. return frame_fires, fires