multi_scale_sampler.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. from paddle.io import Sampler
  2. import paddle.distributed as dist
  3. import numpy as np
  4. import random
  5. import math
  6. class MultiScaleSampler(Sampler):
  7. def __init__(
  8. self,
  9. data_source,
  10. scales,
  11. first_bs=128,
  12. fix_bs=True,
  13. divided_factor=[8, 16],
  14. is_training=True,
  15. ratio_wh=0.8,
  16. max_w=480.0,
  17. seed=None,
  18. ):
  19. """
  20. multi scale samper
  21. Args:
  22. data_source(dataset)
  23. scales(list): several scales for image resolution
  24. first_bs(int): batch size for the first scale in scales
  25. divided_factor(list[w, h]): ImageNet models down-sample images by a factor, ensure that width and height dimensions are multiples are multiple of devided_factor.
  26. is_training(boolean): mode
  27. """
  28. # min. and max. spatial dimensions
  29. self.data_source = data_source
  30. self.data_idx_order_list = np.array(data_source.data_idx_order_list)
  31. self.ds_width = data_source.ds_width
  32. self.seed = data_source.seed
  33. if self.ds_width:
  34. self.wh_ratio = data_source.wh_ratio
  35. self.wh_ratio_sort = data_source.wh_ratio_sort
  36. self.n_data_samples = len(self.data_source)
  37. self.ratio_wh = ratio_wh
  38. self.max_w = max_w
  39. if isinstance(scales[0], list):
  40. width_dims = [i[0] for i in scales]
  41. height_dims = [i[1] for i in scales]
  42. elif isinstance(scales[0], int):
  43. width_dims = scales
  44. height_dims = scales
  45. base_im_w = width_dims[0]
  46. base_im_h = height_dims[0]
  47. base_batch_size = first_bs
  48. # Get the GPU and node related information
  49. num_replicas = dist.get_world_size()
  50. rank = dist.get_rank()
  51. # adjust the total samples to avoid batch dropping
  52. num_samples_per_replica = int(self.n_data_samples * 1.0 / num_replicas)
  53. img_indices = [idx for idx in range(self.n_data_samples)]
  54. self.shuffle = False
  55. if is_training:
  56. # compute the spatial dimensions and corresponding batch size
  57. # ImageNet models down-sample images by a factor of 32.
  58. # Ensure that width and height dimensions are multiples are multiple of 32.
  59. width_dims = [
  60. int((w // divided_factor[0]) * divided_factor[0]) for w in width_dims
  61. ]
  62. height_dims = [
  63. int((h // divided_factor[1]) * divided_factor[1]) for h in height_dims
  64. ]
  65. img_batch_pairs = list()
  66. base_elements = base_im_w * base_im_h * base_batch_size
  67. for h, w in zip(height_dims, width_dims):
  68. if fix_bs:
  69. batch_size = base_batch_size
  70. else:
  71. batch_size = int(max(1, (base_elements / (h * w))))
  72. img_batch_pairs.append((w, h, batch_size))
  73. self.img_batch_pairs = img_batch_pairs
  74. self.shuffle = True
  75. else:
  76. self.img_batch_pairs = [(base_im_w, base_im_h, base_batch_size)]
  77. self.img_indices = img_indices
  78. self.n_samples_per_replica = num_samples_per_replica
  79. self.epoch = 0
  80. self.rank = rank
  81. self.num_replicas = num_replicas
  82. self.batch_list = []
  83. self.current = 0
  84. last_index = num_samples_per_replica * num_replicas
  85. indices_rank_i = self.img_indices[self.rank : last_index : self.num_replicas]
  86. while self.current < self.n_samples_per_replica:
  87. for curr_w, curr_h, curr_bsz in self.img_batch_pairs:
  88. end_index = min(self.current + curr_bsz, self.n_samples_per_replica)
  89. batch_ids = indices_rank_i[self.current : end_index]
  90. n_batch_samples = len(batch_ids)
  91. if n_batch_samples != curr_bsz:
  92. batch_ids += indices_rank_i[: (curr_bsz - n_batch_samples)]
  93. self.current += curr_bsz
  94. if len(batch_ids) > 0:
  95. batch = [curr_w, curr_h, len(batch_ids)]
  96. self.batch_list.append(batch)
  97. random.shuffle(self.batch_list)
  98. self.length = len(self.batch_list)
  99. self.batchs_in_one_epoch = self.iter()
  100. self.batchs_in_one_epoch_id = [i for i in range(len(self.batchs_in_one_epoch))]
  101. def __iter__(self):
  102. if self.seed is None:
  103. random.seed(self.epoch)
  104. self.epoch += 1
  105. else:
  106. random.seed(self.seed)
  107. random.shuffle(self.batchs_in_one_epoch_id)
  108. for batch_tuple_id in self.batchs_in_one_epoch_id:
  109. yield self.batchs_in_one_epoch[batch_tuple_id]
  110. def iter(self):
  111. if self.shuffle:
  112. if self.seed is not None:
  113. random.seed(self.seed)
  114. else:
  115. random.seed(self.epoch)
  116. if not self.ds_width:
  117. random.shuffle(self.img_indices)
  118. random.shuffle(self.img_batch_pairs)
  119. indices_rank_i = self.img_indices[
  120. self.rank : len(self.img_indices) : self.num_replicas
  121. ]
  122. else:
  123. indices_rank_i = self.img_indices[
  124. self.rank : len(self.img_indices) : self.num_replicas
  125. ]
  126. start_index = 0
  127. batchs_in_one_epoch = []
  128. for batch_tuple in self.batch_list:
  129. curr_w, curr_h, curr_bsz = batch_tuple
  130. end_index = min(start_index + curr_bsz, self.n_samples_per_replica)
  131. batch_ids = indices_rank_i[start_index:end_index]
  132. n_batch_samples = len(batch_ids)
  133. if n_batch_samples != curr_bsz:
  134. batch_ids += indices_rank_i[: (curr_bsz - n_batch_samples)]
  135. start_index += curr_bsz
  136. if len(batch_ids) > 0:
  137. if self.ds_width:
  138. wh_ratio_current = self.wh_ratio[self.wh_ratio_sort[batch_ids]]
  139. ratio_current = wh_ratio_current.mean()
  140. ratio_current = (
  141. ratio_current
  142. if ratio_current * curr_h < self.max_w
  143. else self.max_w / curr_h
  144. )
  145. else:
  146. ratio_current = None
  147. batch = [(curr_w, curr_h, b_id, ratio_current) for b_id in batch_ids]
  148. # yield batch
  149. batchs_in_one_epoch.append(batch)
  150. return batchs_in_one_epoch
  151. def set_epoch(self, epoch: int):
  152. self.epoch = epoch
  153. def __len__(self):
  154. return self.length