ctc_alignment.py 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import torch
  2. def ctc_forced_align(
  3. log_probs: torch.Tensor,
  4. targets: torch.Tensor,
  5. input_lengths: torch.Tensor,
  6. target_lengths: torch.Tensor,
  7. blank: int = 0,
  8. ignore_id: int = -1,
  9. ) -> torch.Tensor:
  10. """Align a CTC label sequence to an emission.
  11. Args:
  12. log_probs (Tensor): log probability of CTC emission output.
  13. Tensor of shape `(B, T, C)`. where `B` is the batch size, `T` is the input length,
  14. `C` is the number of characters in alphabet including blank.
  15. targets (Tensor): Target sequence. Tensor of shape `(B, L)`,
  16. where `L` is the target length.
  17. input_lengths (Tensor):
  18. Lengths of the inputs (max value must each be <= `T`). 1-D Tensor of shape `(B,)`.
  19. target_lengths (Tensor):
  20. Lengths of the targets. 1-D Tensor of shape `(B,)`.
  21. blank_id (int, optional): The index of blank symbol in CTC emission. (Default: 0)
  22. ignore_id (int, optional): The index of ignore symbol in CTC emission. (Default: -1)
  23. """
  24. targets[targets == ignore_id] = blank
  25. batch_size, input_time_size, _ = log_probs.size()
  26. bsz_indices = torch.arange(batch_size, device=input_lengths.device)
  27. _t_a_r_g_e_t_s_ = torch.cat(
  28. (
  29. torch.stack((torch.full_like(targets, blank), targets), dim=-1).flatten(start_dim=1),
  30. torch.full_like(targets[:, :1], blank),
  31. ),
  32. dim=-1,
  33. )
  34. diff_labels = torch.cat(
  35. (
  36. torch.as_tensor([[False, False]], device=targets.device).expand(batch_size, -1),
  37. _t_a_r_g_e_t_s_[:, 2:] != _t_a_r_g_e_t_s_[:, :-2],
  38. ),
  39. dim=1,
  40. )
  41. neg_inf = torch.tensor(float("-inf"), device=log_probs.device, dtype=log_probs.dtype)
  42. padding_num = 2
  43. padded_t = padding_num + _t_a_r_g_e_t_s_.size(-1)
  44. best_score = torch.full((batch_size, padded_t), neg_inf, device=log_probs.device, dtype=log_probs.dtype)
  45. best_score[:, padding_num + 0] = log_probs[:, 0, blank]
  46. best_score[:, padding_num + 1] = log_probs[bsz_indices, 0, _t_a_r_g_e_t_s_[:, 1]]
  47. backpointers = torch.zeros((batch_size, input_time_size, padded_t), device=log_probs.device, dtype=targets.dtype)
  48. for t in range(1, input_time_size):
  49. prev = torch.stack(
  50. (best_score[:, 2:], best_score[:, 1:-1], torch.where(diff_labels, best_score[:, :-2], neg_inf))
  51. )
  52. prev_max_value, prev_max_idx = prev.max(dim=0)
  53. best_score[:, padding_num:] = log_probs[:, t].gather(-1, _t_a_r_g_e_t_s_) + prev_max_value
  54. backpointers[:, t, padding_num:] = prev_max_idx
  55. l1l2 = best_score.gather(
  56. -1, torch.stack((padding_num + target_lengths * 2 - 1, padding_num + target_lengths * 2), dim=-1)
  57. )
  58. path = torch.zeros((batch_size, input_time_size), device=best_score.device, dtype=torch.long)
  59. path[bsz_indices, input_lengths - 1] = padding_num + target_lengths * 2 - 1 + l1l2.argmax(dim=-1)
  60. for t in range(input_time_size - 1, 0, -1):
  61. target_indices = path[:, t]
  62. prev_max_idx = backpointers[bsz_indices, t, target_indices]
  63. path[:, t - 1] += target_indices - prev_max_idx
  64. alignments = _t_a_r_g_e_t_s_.gather(dim=-1, index=(path - padding_num).clamp(min=0))
  65. return alignments