You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

distributed_sampler.py 2.4 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  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. # ============================================================================
  15. """Yolo dataset distributed sampler."""
  16. from __future__ import division
  17. import math
  18. import numpy as np
  19. class DistributedSampler:
  20. """Distributed sampler."""
  21. def __init__(self, dataset_size, num_replicas=None, rank=None, shuffle=True):
  22. if num_replicas is None:
  23. print("***********Setting world_size to 1 since it is not passed in ******************")
  24. num_replicas = 1
  25. if rank is None:
  26. print("***********Setting rank to 0 since it is not passed in ******************")
  27. rank = 0
  28. self.dataset_size = dataset_size
  29. self.num_replicas = num_replicas
  30. self.rank = rank
  31. self.epoch = 0
  32. self.num_samples = int(math.ceil(dataset_size * 1.0 / self.num_replicas))
  33. self.total_size = self.num_samples * self.num_replicas
  34. self.shuffle = shuffle
  35. def __iter__(self):
  36. # deterministically shuffle based on epoch
  37. if self.shuffle:
  38. indices = np.random.RandomState(seed=self.epoch).permutation(self.dataset_size)
  39. # np.array type. number from 0 to len(dataset_size)-1, used as index of dataset
  40. indices = indices.tolist()
  41. self.epoch += 1
  42. # change to list type
  43. else:
  44. indices = list(range(self.dataset_size))
  45. # add extra samples to make it evenly divisible
  46. indices += indices[:(self.total_size - len(indices))]
  47. assert len(indices) == self.total_size
  48. # subsample
  49. indices = indices[self.rank:self.total_size:self.num_replicas]
  50. assert len(indices) == self.num_samples
  51. return iter(indices)
  52. def __len__(self):
  53. return self.num_samples