doc_vlm_batch_sampler.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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 ....utils import logging
  15. from .base_batch_sampler import BaseBatchSampler
  16. class DocVLMBatchSampler(BaseBatchSampler):
  17. model_names_only_supports_batchsize_of_one = {"PP-DocBee-2B", "PP-DocBee-7B"}
  18. def __init__(self, model_name, batch_size: int = 1) -> None:
  19. """Initializes the BaseBatchSampler.
  20. Args:
  21. model_name (str): The name of the model.
  22. batch_size (int, optional): The size of each batch. Only support 1.
  23. """
  24. self.model_name = model_name
  25. if (
  26. self.model_name in self.model_names_only_supports_batchsize_of_one
  27. and batch_size != 1
  28. ):
  29. logging.warning(
  30. f"doc vlm batch sampler only support batch size 1 for {self.model_name}, but got {batch_size} and it will not take effect."
  31. )
  32. batch_size = 1
  33. super().__init__(batch_size)
  34. def sample(self, inputs):
  35. """Generate list of input file path.
  36. Args:
  37. inputs (str): file path.
  38. Yields:
  39. list: list of file path.
  40. """
  41. if isinstance(inputs, dict):
  42. inputs = [inputs]
  43. if not (isinstance(inputs, list) and all(isinstance(i, dict) for i in inputs)):
  44. raise TypeError(
  45. f"Not supported input data type! Only `Dict` or `List[Dict]` are supported, but got: {type(inputs)}."
  46. )
  47. batch = []
  48. for input_ in inputs:
  49. batch.append(input_)
  50. if len(batch) == self.batch_size:
  51. yield batch
  52. batch = []
  53. if len(batch) > 0:
  54. yield batch
  55. @BaseBatchSampler.batch_size.setter
  56. def batch_size(self, batch_size):
  57. """Sets the batch size.
  58. Args:
  59. batch_size (int): The batch size to set.
  60. Raises:
  61. Warning: If the batch size is not equal 1.
  62. """
  63. # only support batch size 1
  64. if (
  65. self.model_name in self.model_names_only_supports_batchsize_of_one
  66. and batch_size != 1
  67. ):
  68. logging.warning(
  69. f"doc vlm batch sampler only support batch size 1 for {self.model_name}, but got {batch_size} and it will not take effect."
  70. )
  71. else:
  72. self._batch_size = batch_size