sorted_batch_sampler.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import logging
  2. from typing import Iterator
  3. from typing import Tuple
  4. from funasr.fileio.read_text import load_num_sequence_text
  5. from funasr.samplers.abs_sampler import AbsSampler
  6. class SortedBatchSampler(AbsSampler):
  7. """BatchSampler with sorted samples by length.
  8. Args:
  9. batch_size:
  10. shape_file:
  11. sort_in_batch: 'descending', 'ascending' or None.
  12. sort_batch:
  13. """
  14. def __init__(
  15. self,
  16. batch_size: int,
  17. shape_file: str,
  18. sort_in_batch: str = "descending",
  19. sort_batch: str = "ascending",
  20. drop_last: bool = False,
  21. ):
  22. assert batch_size > 0
  23. self.batch_size = batch_size
  24. self.shape_file = shape_file
  25. self.sort_in_batch = sort_in_batch
  26. self.sort_batch = sort_batch
  27. self.drop_last = drop_last
  28. # utt2shape: (Length, ...)
  29. # uttA 100,...
  30. # uttB 201,...
  31. utt2shape = load_num_sequence_text(shape_file, loader_type="csv_int")
  32. if sort_in_batch == "descending":
  33. # Sort samples in descending order (required by RNN)
  34. keys = sorted(utt2shape, key=lambda k: -utt2shape[k][0])
  35. elif sort_in_batch == "ascending":
  36. # Sort samples in ascending order
  37. keys = sorted(utt2shape, key=lambda k: utt2shape[k][0])
  38. else:
  39. raise ValueError(
  40. f"sort_in_batch must be either one of "
  41. f"ascending, descending, or None: {sort_in_batch}"
  42. )
  43. if len(keys) == 0:
  44. raise RuntimeError(f"0 lines found: {shape_file}")
  45. # Apply max(, 1) to avoid 0-batches
  46. N = max(len(keys) // batch_size, 1)
  47. if not self.drop_last:
  48. # Split keys evenly as possible as. Note that If N != 1,
  49. # the these batches always have size of batch_size at minimum.
  50. self.batch_list = [
  51. keys[i * len(keys) // N : (i + 1) * len(keys) // N] for i in range(N)
  52. ]
  53. else:
  54. self.batch_list = [
  55. tuple(keys[i * batch_size : (i + 1) * batch_size]) for i in range(N)
  56. ]
  57. if len(self.batch_list) == 0:
  58. logging.warning(f"{shape_file} is empty")
  59. if sort_in_batch != sort_batch:
  60. if sort_batch not in ("ascending", "descending"):
  61. raise ValueError(
  62. f"sort_batch must be ascending or descending: {sort_batch}"
  63. )
  64. self.batch_list.reverse()
  65. if len(self.batch_list) == 0:
  66. raise RuntimeError("0 batches")
  67. def __repr__(self):
  68. return (
  69. f"{self.__class__.__name__}("
  70. f"N-batch={len(self)}, "
  71. f"batch_size={self.batch_size}, "
  72. f"shape_file={self.shape_file}, "
  73. f"sort_in_batch={self.sort_in_batch}, "
  74. f"sort_batch={self.sort_batch})"
  75. )
  76. def __len__(self):
  77. return len(self.batch_list)
  78. def __iter__(self) -> Iterator[Tuple[str, ...]]:
  79. return iter(self.batch_list)