ctc.py 6.4 KB

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