common.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. # Copyright (c) 2020 Mobvoi Inc (Binbin Zhang)
  2. # 2024 Alibaba Inc (authors: Xiang Lyu)
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. # Modified from ESPnet(https://github.com/espnet/espnet)
  16. """Unility functions for Transformer."""
  17. from typing import List
  18. import torch
  19. IGNORE_ID = -1
  20. def pad_list(xs: List[torch.Tensor], pad_value: int):
  21. """Perform padding for the list of tensors.
  22. Args:
  23. xs (List): List of Tensors [(T_1, `*`), (T_2, `*`), ..., (T_B, `*`)].
  24. pad_value (float): Value for padding.
  25. Returns:
  26. Tensor: Padded tensor (B, Tmax, `*`).
  27. Examples:
  28. >>> x = [torch.ones(4), torch.ones(2), torch.ones(1)]
  29. >>> x
  30. [tensor([1., 1., 1., 1.]), tensor([1., 1.]), tensor([1.])]
  31. >>> pad_list(x, 0)
  32. tensor([[1., 1., 1., 1.],
  33. [1., 1., 0., 0.],
  34. [1., 0., 0., 0.]])
  35. """
  36. max_len = max([len(item) for item in xs])
  37. batchs = len(xs)
  38. ndim = xs[0].ndim
  39. if ndim == 1:
  40. pad_res = torch.zeros(batchs,
  41. max_len,
  42. dtype=xs[0].dtype,
  43. device=xs[0].device)
  44. elif ndim == 2:
  45. pad_res = torch.zeros(batchs,
  46. max_len,
  47. xs[0].shape[1],
  48. dtype=xs[0].dtype,
  49. device=xs[0].device)
  50. elif ndim == 3:
  51. pad_res = torch.zeros(batchs,
  52. max_len,
  53. xs[0].shape[1],
  54. xs[0].shape[2],
  55. dtype=xs[0].dtype,
  56. device=xs[0].device)
  57. else:
  58. raise ValueError(f"Unsupported ndim: {ndim}")
  59. pad_res.fill_(pad_value)
  60. for i in range(batchs):
  61. pad_res[i, :len(xs[i])] = xs[i]
  62. return pad_res
  63. def th_accuracy(pad_outputs: torch.Tensor, pad_targets: torch.Tensor,
  64. ignore_label: int) -> torch.Tensor:
  65. """Calculate accuracy.
  66. Args:
  67. pad_outputs (Tensor): Prediction tensors (B * Lmax, D).
  68. pad_targets (LongTensor): Target label tensors (B, Lmax).
  69. ignore_label (int): Ignore label id.
  70. Returns:
  71. torch.Tensor: Accuracy value (0.0 - 1.0).
  72. """
  73. pad_pred = pad_outputs.view(pad_targets.size(0), pad_targets.size(1),
  74. pad_outputs.size(1)).argmax(2)
  75. mask = pad_targets != ignore_label
  76. numerator = torch.sum(
  77. pad_pred.masked_select(mask) == pad_targets.masked_select(mask))
  78. denominator = torch.sum(mask)
  79. return (numerator / denominator).detach()