loader.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. """ Object detection loader/collate
  2. Hacked together by Ross Wightman
  3. """
  4. # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License");
  7. # you may not use this file except in compliance with the License.
  8. # You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. import torch
  18. import torch.utils.data
  19. from .transforms import *
  20. from utils.distributed_sampler import OrderedDistributedSampler
  21. from functools import partial
  22. MAX_NUM_INSTANCES = 100
  23. def fast_collate(memory_format, batch):
  24. batch_size = len(batch)
  25. # FIXME this needs to be more robust
  26. target = dict()
  27. for k, v in batch[0][1].items():
  28. if isinstance(v, np.ndarray):
  29. # if a numpy array, assume it relates to object instances, pad to MAX_NUM_INSTANCES
  30. target_shape = (batch_size, MAX_NUM_INSTANCES)
  31. if len(v.shape) > 1:
  32. target_shape = target_shape + v.shape[1:]
  33. target_dtype = torch.float32
  34. elif isinstance(v, (tuple, list)):
  35. # if tuple or list, assume per batch
  36. target_shape = (batch_size, len(v))
  37. target_dtype = torch.float32 if isinstance(v[0], float) else torch.int32
  38. elif isinstance(v, torch.Tensor):
  39. target_dtype = v.dtype
  40. target_shape = (batch_size,) + tuple(v.size())
  41. else:
  42. # scalar, assume per batch
  43. target_shape = batch_size,
  44. target_dtype = torch.float32 if isinstance(v, float) else torch.int64
  45. target[k] = torch.zeros(target_shape, dtype=target_dtype)
  46. tensor = torch.zeros((batch_size, *batch[0][0].shape), dtype=torch.uint8).contiguous(
  47. memory_format=memory_format
  48. )
  49. for i in range(batch_size):
  50. tensor[i] += torch.from_numpy(batch[i][0])
  51. for tk, tv in batch[i][1].items():
  52. if isinstance(tv, np.ndarray) and len(tv.shape):
  53. target[tk][i, 0:tv.shape[0]] = torch.from_numpy(tv)
  54. elif isinstance(tv, torch.Tensor):
  55. target[tk][i] = tv
  56. else:
  57. target[tk][i] = torch.tensor(tv, dtype=target[tk].dtype)
  58. return tensor, target
  59. class PrefetchLoader:
  60. def __init__(self,
  61. loader,
  62. mean=IMAGENET_DEFAULT_MEAN,
  63. std=IMAGENET_DEFAULT_STD):
  64. self.loader = loader
  65. self.mean = torch.tensor([x * 255 for x in mean]).cuda().view(1, 3, 1, 1)
  66. self.std = torch.tensor([x * 255 for x in std]).cuda().view(1, 3, 1, 1)
  67. def __iter__(self):
  68. stream = torch.cuda.Stream()
  69. first = True
  70. for next_input, next_target in self.loader:
  71. with torch.cuda.stream(stream):
  72. next_input = next_input.cuda(non_blocking=True)
  73. next_input = next_input.float().sub_(self.mean).div_(self.std)
  74. next_target = {k: v.cuda(non_blocking=True) for k, v in next_target.items()}
  75. if not first:
  76. yield input, target
  77. else:
  78. first = False
  79. torch.cuda.current_stream().wait_stream(stream)
  80. input = next_input
  81. target = next_target
  82. yield input, target
  83. def __len__(self):
  84. return len(self.loader)
  85. @property
  86. def sampler(self):
  87. return self.loader.batch_sampler
  88. class IterationBasedBatchSampler(torch.utils.data.sampler.BatchSampler):
  89. """
  90. Wraps a BatchSampler, resampling from it until
  91. a specified number of iterations have been sampled
  92. """
  93. def __init__(self, batch_sampler):
  94. self.batch_sampler = batch_sampler
  95. def __iter__(self):
  96. while True:
  97. for batch in self.batch_sampler:
  98. yield batch
  99. def __len__(self):
  100. return len(self.batch_sampler)
  101. def set_epoch(self, epoch):
  102. if hasattr(self.batch_sampler.sampler, "set_epoch"):
  103. self.batch_sampler.sampler.set_epoch(epoch)
  104. def create_loader(
  105. dataset,
  106. input_size,
  107. batch_size,
  108. is_training=False,
  109. use_prefetcher=True,
  110. interpolation='bilinear',
  111. fill_color='mean',
  112. mean=IMAGENET_DEFAULT_MEAN,
  113. std=IMAGENET_DEFAULT_STD,
  114. num_workers=1,
  115. distributed=False,
  116. pin_mem=False,
  117. memory_format=torch.contiguous_format
  118. ):
  119. if isinstance(input_size, tuple):
  120. img_size = input_size[-2:]
  121. else:
  122. img_size = input_size
  123. if is_training:
  124. transform = transforms_coco_train(
  125. img_size,
  126. interpolation=interpolation,
  127. use_prefetcher=use_prefetcher,
  128. fill_color=fill_color,
  129. mean=mean,
  130. std=std)
  131. else:
  132. transform = transforms_coco_eval(
  133. img_size,
  134. interpolation=interpolation,
  135. use_prefetcher=use_prefetcher,
  136. fill_color=fill_color,
  137. mean=mean,
  138. std=std)
  139. dataset.transform = transform
  140. sampler = None
  141. if distributed:
  142. if is_training:
  143. sampler = torch.utils.data.distributed.DistributedSampler(dataset)
  144. else:
  145. # This will add extra duplicate entries to result in equal num
  146. # of samples per-process, will slightly alter validation results
  147. sampler = OrderedDistributedSampler(dataset)
  148. else:
  149. sampler = torch.utils.data.RandomSampler(dataset)
  150. batch_sampler = torch.utils.data.sampler.BatchSampler(
  151. sampler, batch_size, drop_last=False)
  152. if is_training:
  153. batch_sampler = IterationBasedBatchSampler(batch_sampler)
  154. loader = torch.utils.data.DataLoader(
  155. dataset,
  156. shuffle=False,
  157. num_workers=num_workers,
  158. batch_sampler=batch_sampler,
  159. pin_memory=pin_mem,
  160. collate_fn=partial(fast_collate, memory_format) if use_prefetcher else torch.utils.data.dataloader.default_collate,
  161. )
  162. else:
  163. loader = torch.utils.data.DataLoader(
  164. dataset,
  165. batch_size=batch_size,
  166. shuffle=False,
  167. num_workers=num_workers,
  168. sampler=sampler,
  169. pin_memory=pin_mem,
  170. collate_fn=partial(fast_collate, memory_format) if use_prefetcher else torch.utils.data.dataloader.default_collate,
  171. )
  172. if use_prefetcher:
  173. loader = PrefetchLoader(loader, mean=mean, std=std)
  174. return loader