base_batch_sampler.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  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 typing import Union, Tuple, List, Dict, Any, Iterator
  15. from abc import ABC, abstractmethod
  16. class BaseBatchSampler:
  17. """BaseBatchSampler"""
  18. def __init__(self, batch_size: int = 1) -> None:
  19. """Initializes the BaseBatchSampler.
  20. Args:
  21. batch_size (int, optional): The size of each batch. Defaults to 1.
  22. """
  23. super().__init__()
  24. self._batch_size = batch_size
  25. @property
  26. def batch_size(self) -> int:
  27. """Gets the batch size."""
  28. return self._batch_size
  29. @batch_size.setter
  30. def batch_size(self, batch_size: int) -> None:
  31. """Sets the batch size.
  32. Args:
  33. batch_size (int): The batch size to set.
  34. Raises:
  35. AssertionError: If the batch size is not greater than 0.
  36. """
  37. assert batch_size > 0
  38. self._batch_size = batch_size
  39. def __call__(self, input: Any) -> Iterator[List[Any]]:
  40. """
  41. Sample batch data with the specified input.
  42. If input is None and benchmarking is enabled, it will yield batches
  43. of random data for the specified number of iterations.
  44. Otherwise, it will yield from the apply() function.
  45. Args:
  46. input (Any): The input data to sampled.
  47. Yields:
  48. Iterator[List[Any]]: An iterator yielding the batch data.
  49. """
  50. yield from self.sample(input)
  51. @abstractmethod
  52. def sample(self, *args: Tuple[Any], **kwargs: Dict[str, Any]) -> Iterator[list]:
  53. """sample batch data"""
  54. raise NotImplementedError
  55. @abstractmethod
  56. def _rand_batch(self, batch_size: int) -> List[Any]:
  57. """rand batch data
  58. Args:
  59. batch_size (int): batch size
  60. """
  61. raise NotImplementedError