cif.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  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. class CifPredictorV2(nn.Module):
  16. def __init__(self, model):
  17. super().__init__()
  18. self.pad = model.pad
  19. self.cif_conv1d = model.cif_conv1d
  20. self.cif_output = model.cif_output
  21. self.threshold = model.threshold
  22. self.smooth_factor = model.smooth_factor
  23. self.noise_threshold = model.noise_threshold
  24. self.tail_threshold = model.tail_threshold
  25. def forward(self, hidden: torch.Tensor,
  26. mask: torch.Tensor,
  27. ):
  28. h = hidden
  29. context = h.transpose(1, 2)
  30. queries = self.pad(context)
  31. output = torch.relu(self.cif_conv1d(queries))
  32. output = output.transpose(1, 2)
  33. output = self.cif_output(output)
  34. alphas = torch.sigmoid(output)
  35. alphas = torch.nn.functional.relu(alphas * self.smooth_factor - self.noise_threshold)
  36. mask = mask.transpose(-1, -2).float()
  37. alphas = alphas * mask
  38. alphas = alphas.squeeze(-1)
  39. token_num = alphas.sum(-1)
  40. acoustic_embeds, cif_peak = cif(hidden, alphas, self.threshold)
  41. return acoustic_embeds, token_num, alphas, cif_peak
  42. def tail_process_fn(self, hidden, alphas, token_num=None, mask=None):
  43. b, t, d = hidden.size()
  44. tail_threshold = self.tail_threshold
  45. zeros_t = torch.zeros((b, 1), dtype=torch.float32, device=alphas.device)
  46. ones_t = torch.ones_like(zeros_t)
  47. mask_1 = torch.cat([mask, zeros_t], dim=1)
  48. mask_2 = torch.cat([ones_t, mask], dim=1)
  49. mask = mask_2 - mask_1
  50. tail_threshold = mask * tail_threshold
  51. alphas = torch.cat([alphas, tail_threshold], dim=1)
  52. zeros = torch.zeros((b, 1, d), dtype=hidden.dtype).to(hidden.device)
  53. hidden = torch.cat([hidden, zeros], dim=1)
  54. token_num = alphas.sum(dim=-1)
  55. token_num_floor = torch.floor(token_num)
  56. return hidden, alphas, token_num_floor
  57. @torch.jit.script
  58. def cif(hidden, alphas, threshold: float):
  59. batch_size, len_time, hidden_size = hidden.size()
  60. threshold = torch.tensor([threshold], dtype=alphas.dtype).to(alphas.device)
  61. # loop varss
  62. integrate = torch.zeros([batch_size], device=hidden.device)
  63. frame = torch.zeros([batch_size, hidden_size], device=hidden.device)
  64. # intermediate vars along time
  65. list_fires = []
  66. list_frames = []
  67. for t in range(len_time):
  68. alpha = alphas[:, t]
  69. distribution_completion = torch.ones([batch_size], device=hidden.device) - integrate
  70. integrate += alpha
  71. list_fires.append(integrate)
  72. fire_place = integrate >= threshold
  73. integrate = torch.where(fire_place,
  74. integrate - torch.ones([batch_size], device=hidden.device),
  75. integrate)
  76. cur = torch.where(fire_place,
  77. distribution_completion,
  78. alpha)
  79. remainds = alpha - cur
  80. frame += cur[:, None] * hidden[:, t, :]
  81. list_frames.append(frame)
  82. frame = torch.where(fire_place[:, None].repeat(1, hidden_size),
  83. remainds[:, None] * hidden[:, t, :],
  84. frame)
  85. fires = torch.stack(list_fires, 1)
  86. frames = torch.stack(list_frames, 1)
  87. list_ls = []
  88. len_labels = torch.round(alphas.sum(-1)).int()
  89. max_label_len = len_labels.max()
  90. for b in range(batch_size):
  91. fire = fires[b, :]
  92. l = torch.index_select(frames[b, :, :], 0, torch.nonzero(fire >= threshold).squeeze())
  93. pad_l = torch.zeros([int(max_label_len - l.size(0)), int(hidden_size)], device=hidden.device)
  94. list_ls.append(torch.cat([l, pad_l], 0))
  95. return torch.stack(list_ls, 0), fires