ctc.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. import logging
  2. import torch
  3. import torch.nn.functional as F
  4. class CTC(torch.nn.Module):
  5. """CTC module.
  6. Args:
  7. odim: dimension of outputs
  8. encoder_output_size: number of encoder projection units
  9. dropout_rate: dropout rate (0.0 ~ 1.0)
  10. ctc_type: builtin or warpctc
  11. reduce: reduce the CTC loss into a scalar
  12. """
  13. def __init__(
  14. self,
  15. odim: int,
  16. encoder_output_size: int,
  17. dropout_rate: float = 0.0,
  18. ctc_type: str = "builtin",
  19. reduce: bool = True,
  20. ignore_nan_grad: bool = True,
  21. ):
  22. super().__init__()
  23. eprojs = encoder_output_size
  24. self.dropout_rate = dropout_rate
  25. self.ctc_lo = torch.nn.Linear(eprojs, odim)
  26. self.ctc_type = ctc_type
  27. self.ignore_nan_grad = ignore_nan_grad
  28. if self.ctc_type == "builtin":
  29. self.ctc_loss = torch.nn.CTCLoss(reduction="none")
  30. elif self.ctc_type == "warpctc":
  31. import warpctc_pytorch as warp_ctc
  32. if ignore_nan_grad:
  33. logging.warning("ignore_nan_grad option is not supported for warp_ctc")
  34. self.ctc_loss = warp_ctc.CTCLoss(size_average=True, reduce=reduce)
  35. else:
  36. raise ValueError(
  37. f'ctc_type must be "builtin" or "warpctc": {self.ctc_type}'
  38. )
  39. self.reduce = reduce
  40. def loss_fn(self, th_pred, th_target, th_ilen, th_olen) -> torch.Tensor:
  41. if self.ctc_type == "builtin":
  42. th_pred = th_pred.log_softmax(2)
  43. loss = self.ctc_loss(th_pred, th_target, th_ilen, th_olen)
  44. if loss.requires_grad and self.ignore_nan_grad:
  45. # ctc_grad: (L, B, O)
  46. ctc_grad = loss.grad_fn(torch.ones_like(loss))
  47. ctc_grad = ctc_grad.sum([0, 2])
  48. indices = torch.isfinite(ctc_grad)
  49. size = indices.long().sum()
  50. if size == 0:
  51. # Return as is
  52. logging.warning(
  53. "All samples in this mini-batch got nan grad."
  54. " Returning nan value instead of CTC loss"
  55. )
  56. elif size != th_pred.size(1):
  57. logging.warning(
  58. f"{th_pred.size(1) - size}/{th_pred.size(1)}"
  59. " samples got nan grad."
  60. " These were ignored for CTC loss."
  61. )
  62. # Create mask for target
  63. target_mask = torch.full(
  64. [th_target.size(0)],
  65. 1,
  66. dtype=torch.bool,
  67. device=th_target.device,
  68. )
  69. s = 0
  70. for ind, le in enumerate(th_olen):
  71. if not indices[ind]:
  72. target_mask[s : s + le] = 0
  73. s += le
  74. # Calc loss again using maksed data
  75. loss = self.ctc_loss(
  76. th_pred[:, indices, :],
  77. th_target[target_mask],
  78. th_ilen[indices],
  79. th_olen[indices],
  80. )
  81. else:
  82. size = th_pred.size(1)
  83. if self.reduce:
  84. # Batch-size average
  85. loss = loss.sum() / size
  86. else:
  87. loss = loss / size
  88. return loss
  89. elif self.ctc_type == "warpctc":
  90. # warpctc only supports float32
  91. th_pred = th_pred.to(dtype=torch.float32)
  92. th_target = th_target.cpu().int()
  93. th_ilen = th_ilen.cpu().int()
  94. th_olen = th_olen.cpu().int()
  95. loss = self.ctc_loss(th_pred, th_target, th_ilen, th_olen)
  96. if self.reduce:
  97. # NOTE: sum() is needed to keep consistency since warpctc
  98. # return as tensor w/ shape (1,)
  99. # but builtin return as tensor w/o shape (scalar).
  100. loss = loss.sum()
  101. return loss
  102. elif self.ctc_type == "gtnctc":
  103. log_probs = torch.nn.functional.log_softmax(th_pred, dim=2)
  104. return self.ctc_loss(log_probs, th_target, th_ilen, 0, "none")
  105. else:
  106. raise NotImplementedError
  107. def forward(self, hs_pad, hlens, ys_pad, ys_lens):
  108. """Calculate CTC loss.
  109. Args:
  110. hs_pad: batch of padded hidden state sequences (B, Tmax, D)
  111. hlens: batch of lengths of hidden state sequences (B)
  112. ys_pad: batch of padded character id sequence tensor (B, Lmax)
  113. ys_lens: batch of lengths of character sequence (B)
  114. """
  115. # hs_pad: (B, L, NProj) -> ys_hat: (B, L, Nvocab)
  116. ys_hat = self.ctc_lo(F.dropout(hs_pad, p=self.dropout_rate))
  117. if self.ctc_type == "gtnctc":
  118. # gtn expects list form for ys
  119. ys_true = [y[y != -1] for y in ys_pad] # parse padded ys
  120. else:
  121. # ys_hat: (B, L, D) -> (L, B, D)
  122. ys_hat = ys_hat.transpose(0, 1)
  123. # (B, L) -> (BxL,)
  124. ys_true = torch.cat([ys_pad[i, :l] for i, l in enumerate(ys_lens)])
  125. loss = self.loss_fn(ys_hat, ys_true, hlens, ys_lens).to(
  126. device=hs_pad.device, dtype=hs_pad.dtype
  127. )
  128. return loss
  129. def softmax(self, hs_pad):
  130. """softmax of frame activations
  131. Args:
  132. Tensor hs_pad: 3d tensor (B, Tmax, eprojs)
  133. Returns:
  134. torch.Tensor: softmax applied 3d tensor (B, Tmax, odim)
  135. """
  136. return F.softmax(self.ctc_lo(hs_pad), dim=2)
  137. def log_softmax(self, hs_pad):
  138. """log_softmax of frame activations
  139. Args:
  140. Tensor hs_pad: 3d tensor (B, Tmax, eprojs)
  141. Returns:
  142. torch.Tensor: log softmax applied 3d tensor (B, Tmax, odim)
  143. """
  144. return F.log_softmax(self.ctc_lo(hs_pad), dim=2)
  145. def argmax(self, hs_pad):
  146. """argmax of frame activations
  147. Args:
  148. torch.Tensor hs_pad: 3d tensor (B, Tmax, eprojs)
  149. Returns:
  150. torch.Tensor: argmax applied 2d tensor (B, Tmax)
  151. """
  152. return torch.argmax(self.ctc_lo(hs_pad), dim=2)