base_batch_sampler.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. # Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from abc import abstractmethod
  15. from typing import Any, Dict, Iterator, List, Tuple
  16. class Batch:
  17. def __init__(self):
  18. self.instances = []
  19. self.input_paths = []
  20. def append(self, instance, input_path):
  21. self.instances.append(instance)
  22. self.input_paths.append(input_path)
  23. def reset(self):
  24. self.instances = []
  25. self.input_paths = []
  26. def __len__(self):
  27. return len(self.instances)
  28. class BaseBatchSampler:
  29. """BaseBatchSampler"""
  30. def __init__(self, batch_size: int = 1) -> None:
  31. """Initializes the BaseBatchSampler.
  32. Args:
  33. batch_size (int, optional): The size of each batch. Defaults to 1.
  34. """
  35. super().__init__()
  36. self._batch_size = batch_size
  37. @property
  38. def batch_size(self) -> int:
  39. """Gets the batch size."""
  40. return self._batch_size
  41. @batch_size.setter
  42. def batch_size(self, batch_size: int) -> None:
  43. """Sets the batch size.
  44. Args:
  45. batch_size (int): The batch size to set.
  46. Raises:
  47. AssertionError: If the batch size is not greater than 0.
  48. """
  49. assert batch_size > 0
  50. self._batch_size = batch_size
  51. def __call__(self, input: Any) -> Iterator[List[Any]]:
  52. """
  53. Sample batch data with the specified input.
  54. If input is None and benchmarking is enabled, it will yield batches
  55. of random data for the specified number of iterations.
  56. Otherwise, it will yield from the apply() function.
  57. Args:
  58. input (Any): The input data to sampled.
  59. Yields:
  60. Iterator[List[Any]]: An iterator yielding the batch data.
  61. """
  62. yield from self.sample(input)
  63. @abstractmethod
  64. def sample(self, *args: Tuple[Any], **kwargs: Dict[str, Any]) -> Iterator[list]:
  65. """sample batch data"""
  66. raise NotImplementedError
  67. @abstractmethod
  68. def _rand_batch(self, batch_size: int) -> List[Any]:
  69. """rand batch data
  70. Args:
  71. batch_size (int): batch size
  72. """
  73. raise NotImplementedError