dataloader.py 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479
  1. r"""Definition of the DataLoader and associated iterators that subclass _BaseDataLoaderIter
  2. To support these two classes, in `./_utils` we define many utility methods and
  3. functions to be run in multiprocessing. E.g., the data loading worker loop is
  4. in `./_utils/worker.py`.
  5. """
  6. import functools
  7. import itertools
  8. import logging
  9. import os
  10. import queue
  11. import threading
  12. import warnings
  13. from typing import Any, Callable, Iterable, TypeVar, Generic, Sequence, List, Optional, Union
  14. import multiprocessing as python_multiprocessing
  15. import torch
  16. import torch.distributed as dist
  17. import torch.multiprocessing as multiprocessing
  18. import torch.utils.data.graph_settings
  19. from torch._utils import ExceptionWrapper
  20. from . import (
  21. IterDataPipe,
  22. MapDataPipe,
  23. IterableDataset,
  24. Sampler,
  25. SequentialSampler,
  26. RandomSampler,
  27. BatchSampler,
  28. Dataset,)
  29. from torch.utils.data.datapipes.datapipe import _IterDataPipeSerializationWrapper, _MapDataPipeSerializationWrapper
  30. from torch.utils.data.datapipes.iter.sharding import SHARDING_PRIORITIES
  31. from . import _utils
  32. __all__ = [
  33. "DataLoader",
  34. "get_worker_info",
  35. "default_collate",
  36. "default_convert",
  37. ]
  38. T_co = TypeVar('T_co', covariant=True)
  39. T = TypeVar('T')
  40. _worker_init_fn_t = Callable[[int], None]
  41. # Ideally we would parameterize `DataLoader` by the return type of `collate_fn`, but there is currently no way to have that
  42. # type parameter set to a default value if the user doesn't pass in a custom 'collate_fn'.
  43. # See https://github.com/python/mypy/issues/3737.
  44. _collate_fn_t = Callable[[List[T]], Any]
  45. # These functions used to be defined in this file. However, it was moved to
  46. # _utils/collate.py. Although it is rather hard to access this from user land
  47. # (one has to explicitly directly `import torch.utils.data.dataloader`), there
  48. # probably is user code out there using it. This aliasing maintains BC in this
  49. # aspect.
  50. default_collate: _collate_fn_t = _utils.collate.default_collate
  51. default_convert = _utils.collate.default_convert
  52. get_worker_info = _utils.worker.get_worker_info
  53. logger = logging.getLogger(__name__)
  54. class _DatasetKind:
  55. Map = 0
  56. Iterable = 1
  57. @staticmethod
  58. def create_fetcher(kind, dataset, auto_collation, collate_fn, drop_last):
  59. if kind == _DatasetKind.Map:
  60. return _utils.fetch._MapDatasetFetcher(dataset, auto_collation, collate_fn, drop_last)
  61. else:
  62. return _utils.fetch._IterableDatasetFetcher(dataset, auto_collation, collate_fn, drop_last)
  63. class _InfiniteConstantSampler(Sampler):
  64. r"""Analogous to ``itertools.repeat(None, None)``.
  65. Used as sampler for :class:`~torch.utils.data.IterableDataset`.
  66. Args:
  67. data_source (Dataset): dataset to sample from
  68. """
  69. def __init__(self):
  70. super().__init__(None)
  71. def __iter__(self):
  72. while True:
  73. yield None
  74. def _get_distributed_settings():
  75. if dist.is_available() and dist.is_initialized():
  76. return dist.get_world_size(), dist.get_rank()
  77. else:
  78. return 1, 0
  79. def _sharding_worker_init_fn(worker_init_fn, world_size, rank_id, worker_id):
  80. info = torch.utils.data.get_worker_info()
  81. assert info is not None
  82. total_workers = info.num_workers
  83. datapipe = info.dataset
  84. assert isinstance(datapipe, (IterDataPipe, MapDataPipe))
  85. # To distribute elements across distributed process evenly, we should shard data on distributed
  86. # processes first then shard on worker processes
  87. torch.utils.data.graph_settings.apply_sharding(
  88. datapipe, world_size, rank_id, sharding_group=SHARDING_PRIORITIES.DISTRIBUTED)
  89. torch.utils.data.graph_settings.apply_sharding(
  90. datapipe, total_workers, worker_id, sharding_group=SHARDING_PRIORITIES.MULTIPROCESSING)
  91. if worker_init_fn is not None:
  92. worker_init_fn(worker_id)
  93. def _share_dist_seed(generator, pg):
  94. _shared_seed = torch.empty((), dtype=torch.int64).random_(generator=generator)
  95. if isinstance(pg, dist.ProcessGroup):
  96. dist.broadcast(_shared_seed, src=0, group=pg)
  97. return _shared_seed.item()
  98. class DataLoader(Generic[T_co]):
  99. r"""
  100. Data loader. Combines a dataset and a sampler, and provides an iterable over
  101. the given dataset.
  102. The :class:`~torch.utils.data.DataLoader` supports both map-style and
  103. iterable-style datasets with single- or multi-process loading, customizing
  104. loading order and optional automatic batching (collation) and memory pinning.
  105. See :py:mod:`torch.utils.data` documentation page for more details.
  106. Args:
  107. dataset (Dataset): dataset from which to load the data.
  108. batch_size (int, optional): how many samples per batch to load
  109. (default: ``1``).
  110. shuffle (bool, optional): set to ``True`` to have the data reshuffled
  111. at every epoch (default: ``False``).
  112. sampler (Sampler or Iterable, optional): defines the strategy to draw
  113. samples from the dataset. Can be any ``Iterable`` with ``__len__``
  114. implemented. If specified, :attr:`shuffle` must not be specified.
  115. batch_sampler (Sampler or Iterable, optional): like :attr:`sampler`, but
  116. returns a batch of indices at a time. Mutually exclusive with
  117. :attr:`batch_size`, :attr:`shuffle`, :attr:`sampler`,
  118. and :attr:`drop_last`.
  119. num_workers (int, optional): how many subprocesses to use for data
  120. loading. ``0`` means that the data will be loaded in the main process.
  121. (default: ``0``)
  122. collate_fn (Callable, optional): merges a list of samples to form a
  123. mini-batch of Tensor(s). Used when using batched loading from a
  124. map-style dataset.
  125. pin_memory (bool, optional): If ``True``, the data loader will copy Tensors
  126. into device/CUDA pinned memory before returning them. If your data elements
  127. are a custom type, or your :attr:`collate_fn` returns a batch that is a custom type,
  128. see the example below.
  129. drop_last (bool, optional): set to ``True`` to drop the last incomplete batch,
  130. if the dataset size is not divisible by the batch size. If ``False`` and
  131. the size of dataset is not divisible by the batch size, then the last batch
  132. will be smaller. (default: ``False``)
  133. timeout (numeric, optional): if positive, the timeout value for collecting a batch
  134. from workers. Should always be non-negative. (default: ``0``)
  135. worker_init_fn (Callable, optional): If not ``None``, this will be called on each
  136. worker subprocess with the worker id (an int in ``[0, num_workers - 1]``) as
  137. input, after seeding and before data loading. (default: ``None``)
  138. generator (torch.Generator, optional): If not ``None``, this RNG will be used
  139. by RandomSampler to generate random indexes and multiprocessing to generate
  140. `base_seed` for workers. (default: ``None``)
  141. prefetch_factor (int, optional, keyword-only arg): Number of batches loaded
  142. in advance by each worker. ``2`` means there will be a total of
  143. 2 * num_workers batches prefetched across all workers. (default value depends
  144. on the set value for num_workers. If value of num_workers=0 default is ``None``.
  145. Otherwise if value of num_workers>0 default is ``2``).
  146. persistent_workers (bool, optional): If ``True``, the data loader will not shutdown
  147. the worker processes after a dataset has been consumed once. This allows to
  148. maintain the workers `Dataset` instances alive. (default: ``False``)
  149. pin_memory_device (str, optional): the data loader will copy Tensors
  150. into device pinned memory before returning them if pin_memory is set to true.
  151. .. warning:: If the ``spawn`` start method is used, :attr:`worker_init_fn`
  152. cannot be an unpicklable object, e.g., a lambda function. See
  153. :ref:`multiprocessing-best-practices` on more details related
  154. to multiprocessing in PyTorch.
  155. .. warning:: ``len(dataloader)`` heuristic is based on the length of the sampler used.
  156. When :attr:`dataset` is an :class:`~torch.utils.data.IterableDataset`,
  157. it instead returns an estimate based on ``len(dataset) / batch_size``, with proper
  158. rounding depending on :attr:`drop_last`, regardless of multi-process loading
  159. configurations. This represents the best guess PyTorch can make because PyTorch
  160. trusts user :attr:`dataset` code in correctly handling multi-process
  161. loading to avoid duplicate data.
  162. However, if sharding results in multiple workers having incomplete last batches,
  163. this estimate can still be inaccurate, because (1) an otherwise complete batch can
  164. be broken into multiple ones and (2) more than one batch worth of samples can be
  165. dropped when :attr:`drop_last` is set. Unfortunately, PyTorch can not detect such
  166. cases in general.
  167. See `Dataset Types`_ for more details on these two types of datasets and how
  168. :class:`~torch.utils.data.IterableDataset` interacts with
  169. `Multi-process data loading`_.
  170. .. warning:: See :ref:`reproducibility`, and :ref:`dataloader-workers-random-seed`, and
  171. :ref:`data-loading-randomness` notes for random seed related questions.
  172. """
  173. dataset: Dataset[T_co]
  174. batch_size: Optional[int]
  175. num_workers: int
  176. pin_memory: bool
  177. drop_last: bool
  178. timeout: float
  179. sampler: Union[Sampler, Iterable]
  180. pin_memory_device: str
  181. prefetch_factor: Optional[int]
  182. _iterator : Optional['_BaseDataLoaderIter']
  183. __initialized = False
  184. def __init__(self, dataset: Dataset[T_co], batch_size: Optional[int] = 1,
  185. shuffle: Optional[bool] = None, sampler: Union[Sampler, Iterable, None] = None,
  186. batch_sampler: Union[Sampler[Sequence], Iterable[Sequence], None] = None,
  187. num_workers: int = 0, collate_fn: Optional[_collate_fn_t] = None,
  188. pin_memory: bool = False, drop_last: bool = False,
  189. timeout: float = 0, worker_init_fn: Optional[_worker_init_fn_t] = None,
  190. multiprocessing_context=None, generator=None,
  191. *, prefetch_factor: Optional[int] = None,
  192. persistent_workers: bool = False,
  193. pin_memory_device: str = ""):
  194. torch._C._log_api_usage_once("python.data_loader")
  195. if num_workers < 0:
  196. raise ValueError('num_workers option should be non-negative; '
  197. 'use num_workers=0 to disable multiprocessing.')
  198. if timeout < 0:
  199. raise ValueError('timeout option should be non-negative')
  200. if num_workers == 0 and prefetch_factor is not None:
  201. raise ValueError('prefetch_factor option could only be specified in multiprocessing.'
  202. 'let num_workers > 0 to enable multiprocessing, otherwise set prefetch_factor to None.')
  203. elif num_workers > 0 and prefetch_factor is None:
  204. prefetch_factor = 2
  205. elif prefetch_factor is not None and prefetch_factor < 0:
  206. raise ValueError('prefetch_factor option should be non-negative')
  207. if persistent_workers and num_workers == 0:
  208. raise ValueError('persistent_workers option needs num_workers > 0')
  209. self.dataset = dataset
  210. self.num_workers = num_workers
  211. self.prefetch_factor = prefetch_factor
  212. self.pin_memory = pin_memory
  213. self.pin_memory_device = pin_memory_device
  214. self.timeout = timeout
  215. self.worker_init_fn = worker_init_fn
  216. self.multiprocessing_context = multiprocessing_context
  217. # Adds forward compatibilities so classic DataLoader can work with DataPipes:
  218. # _DataPipeSerializationWrapper container makes it easier to serialize without redefining pickler
  219. if isinstance(self.dataset, IterDataPipe):
  220. self.dataset = _IterDataPipeSerializationWrapper(self.dataset)
  221. elif isinstance(self.dataset, MapDataPipe):
  222. self.dataset = _MapDataPipeSerializationWrapper(self.dataset)
  223. # Arg-check dataset related before checking samplers because we want to
  224. # tell users that iterable-style datasets are incompatible with custom
  225. # samplers first, so that they don't learn that this combo doesn't work
  226. # after spending time fixing the custom sampler errors.
  227. if isinstance(dataset, IterableDataset):
  228. self._dataset_kind = _DatasetKind.Iterable
  229. # NOTE [ Custom Samplers and IterableDataset ]
  230. #
  231. # `IterableDataset` does not support custom `batch_sampler` or
  232. # `sampler` since the key is irrelevant (unless we support
  233. # generator-style dataset one day...).
  234. #
  235. # For `sampler`, we always create a dummy sampler. This is an
  236. # infinite sampler even when the dataset may have an implemented
  237. # finite `__len__` because in multi-process data loading, naive
  238. # settings will return duplicated data (which may be desired), and
  239. # thus using a sampler with length matching that of dataset will
  240. # cause data lost (you may have duplicates of the first couple
  241. # batches, but never see anything afterwards). Therefore,
  242. # `Iterabledataset` always uses an infinite sampler, an instance of
  243. # `_InfiniteConstantSampler` defined above.
  244. #
  245. # A custom `batch_sampler` essentially only controls the batch size.
  246. # However, it is unclear how useful it would be since an iterable-style
  247. # dataset can handle that within itself. Moreover, it is pointless
  248. # in multi-process data loading as the assignment order of batches
  249. # to workers is an implementation detail so users can not control
  250. # how to batchify each worker's iterable. Thus, we disable this
  251. # option. If this turns out to be useful in future, we can re-enable
  252. # this, and support custom samplers that specify the assignments to
  253. # specific workers.
  254. if isinstance(dataset, IterDataPipe):
  255. if shuffle is not None:
  256. dataset = torch.utils.data.graph_settings.apply_shuffle_settings(dataset, shuffle=shuffle)
  257. # We cannot check `shuffle is not None` here, since previously `shuffle=False` was the default.
  258. elif shuffle not in {False, None}:
  259. raise ValueError(
  260. "DataLoader with IterableDataset: expected unspecified "
  261. "shuffle option, but got shuffle={}".format(shuffle))
  262. if sampler is not None:
  263. # See NOTE [ Custom Samplers and IterableDataset ]
  264. raise ValueError(
  265. "DataLoader with IterableDataset: expected unspecified "
  266. "sampler option, but got sampler={}".format(sampler))
  267. elif batch_sampler is not None:
  268. # See NOTE [ Custom Samplers and IterableDataset ]
  269. raise ValueError(
  270. "DataLoader with IterableDataset: expected unspecified "
  271. "batch_sampler option, but got batch_sampler={}".format(batch_sampler))
  272. else:
  273. shuffle = bool(shuffle)
  274. self._dataset_kind = _DatasetKind.Map
  275. if sampler is not None and shuffle:
  276. raise ValueError('sampler option is mutually exclusive with '
  277. 'shuffle')
  278. if batch_sampler is not None:
  279. # auto_collation with custom batch_sampler
  280. if batch_size != 1 or shuffle or sampler is not None or drop_last:
  281. raise ValueError('batch_sampler option is mutually exclusive '
  282. 'with batch_size, shuffle, sampler, and '
  283. 'drop_last')
  284. batch_size = None
  285. drop_last = False
  286. elif batch_size is None:
  287. # no auto_collation
  288. if drop_last:
  289. raise ValueError('batch_size=None option disables auto-batching '
  290. 'and is mutually exclusive with drop_last')
  291. if sampler is None: # give default samplers
  292. if self._dataset_kind == _DatasetKind.Iterable:
  293. # See NOTE [ Custom Samplers and IterableDataset ]
  294. sampler = _InfiniteConstantSampler()
  295. else: # map-style
  296. if shuffle:
  297. sampler = RandomSampler(dataset, generator=generator) # type: ignore[arg-type]
  298. else:
  299. sampler = SequentialSampler(dataset) # type: ignore[arg-type]
  300. if batch_size is not None and batch_sampler is None:
  301. # auto_collation without custom batch_sampler
  302. batch_sampler = BatchSampler(sampler, batch_size, drop_last)
  303. self.batch_size = batch_size
  304. self.drop_last = drop_last
  305. self.sampler = sampler
  306. self.batch_sampler = batch_sampler
  307. self.generator = generator
  308. if collate_fn is None:
  309. if self._auto_collation:
  310. collate_fn = _utils.collate.default_collate
  311. else:
  312. collate_fn = _utils.collate.default_convert
  313. self.collate_fn = collate_fn
  314. self.persistent_workers = persistent_workers
  315. self.__initialized = True
  316. self._IterableDataset_len_called = None # See NOTE [ IterableDataset and __len__ ]
  317. self._iterator = None
  318. self.check_worker_number_rationality()
  319. torch.set_vital('Dataloader', 'enabled', 'True') # type: ignore[attr-defined]
  320. def _get_iterator(self) -> '_BaseDataLoaderIter':
  321. if self.num_workers == 0:
  322. return _SingleProcessDataLoaderIter(self)
  323. else:
  324. self.check_worker_number_rationality()
  325. return _MultiProcessingDataLoaderIter(self)
  326. @property
  327. def multiprocessing_context(self):
  328. return self.__multiprocessing_context
  329. @multiprocessing_context.setter
  330. def multiprocessing_context(self, multiprocessing_context):
  331. if multiprocessing_context is not None:
  332. if self.num_workers > 0:
  333. if isinstance(multiprocessing_context, str):
  334. valid_start_methods = multiprocessing.get_all_start_methods()
  335. if multiprocessing_context not in valid_start_methods:
  336. raise ValueError(
  337. ('multiprocessing_context option '
  338. 'should specify a valid start method in {!r}, but got '
  339. 'multiprocessing_context={!r}').format(valid_start_methods, multiprocessing_context))
  340. # error: Argument 1 to "get_context" has incompatible type "Union[str, bytes]"; expected "str" [arg-type]
  341. multiprocessing_context = multiprocessing.get_context(multiprocessing_context) # type: ignore[arg-type]
  342. if not isinstance(multiprocessing_context, python_multiprocessing.context.BaseContext):
  343. raise TypeError(('multiprocessing_context option should be a valid context '
  344. 'object or a string specifying the start method, but got '
  345. 'multiprocessing_context={}').format(multiprocessing_context))
  346. else:
  347. raise ValueError(('multiprocessing_context can only be used with '
  348. 'multi-process loading (num_workers > 0), but got '
  349. 'num_workers={}').format(self.num_workers))
  350. self.__multiprocessing_context = multiprocessing_context
  351. def __setattr__(self, attr, val):
  352. if self.__initialized and attr in (
  353. 'batch_size', 'batch_sampler', 'sampler', 'drop_last', 'dataset', 'persistent_workers'):
  354. raise ValueError('{} attribute should not be set after {} is '
  355. 'initialized'.format(attr, self.__class__.__name__))
  356. super().__setattr__(attr, val)
  357. # We quote '_BaseDataLoaderIter' since it isn't defined yet and the definition can't be moved up
  358. # since '_BaseDataLoaderIter' references 'DataLoader'.
  359. def __iter__(self) -> '_BaseDataLoaderIter':
  360. # When using a single worker the returned iterator should be
  361. # created everytime to avoid reseting its state
  362. # However, in the case of a multiple workers iterator
  363. # the iterator is only created once in the lifetime of the
  364. # DataLoader object so that workers can be reused
  365. if self.persistent_workers and self.num_workers > 0:
  366. if self._iterator is None:
  367. self._iterator = self._get_iterator()
  368. else:
  369. self._iterator._reset(self)
  370. return self._iterator
  371. else:
  372. return self._get_iterator()
  373. @property
  374. def _auto_collation(self):
  375. return self.batch_sampler is not None
  376. @property
  377. def _index_sampler(self):
  378. # The actual sampler used for generating indices for `_DatasetFetcher`
  379. # (see _utils/fetch.py) to read data at each time. This would be
  380. # `.batch_sampler` if in auto-collation mode, and `.sampler` otherwise.
  381. # We can't change `.sampler` and `.batch_sampler` attributes for BC
  382. # reasons.
  383. if self._auto_collation:
  384. return self.batch_sampler
  385. else:
  386. return self.sampler
  387. def __len__(self) -> int:
  388. if self._dataset_kind == _DatasetKind.Iterable:
  389. # NOTE [ IterableDataset and __len__ ]
  390. #
  391. # For `IterableDataset`, `__len__` could be inaccurate when one naively
  392. # does multi-processing data loading, since the samples will be duplicated.
  393. # However, no real use case should be actually using that behavior, so
  394. # it should count as a user error. We should generally trust user
  395. # code to do the proper thing (e.g., configure each replica differently
  396. # in `__iter__`), and give us the correct `__len__` if they choose to
  397. # implement it (this will still throw if the dataset does not implement
  398. # a `__len__`).
  399. #
  400. # To provide a further warning, we track if `__len__` was called on the
  401. # `DataLoader`, save the returned value in `self._len_called`, and warn
  402. # if the iterator ends up yielding more than this number of samples.
  403. # Cannot statically verify that dataset is Sized
  404. length = self._IterableDataset_len_called = len(self.dataset) # type: ignore[assignment, arg-type]
  405. if self.batch_size is not None: # IterableDataset doesn't allow custom sampler or batch_sampler
  406. from math import ceil
  407. if self.drop_last:
  408. length = length // self.batch_size
  409. else:
  410. length = ceil(length / self.batch_size)
  411. return length
  412. else:
  413. return len(self._index_sampler)
  414. def check_worker_number_rationality(self):
  415. # This function check whether the dataloader's worker number is rational based on
  416. # current system's resource. Current rule is that if the number of workers this
  417. # Dataloader will create is bigger than the number of logical cpus that is allowed to
  418. # use, than we will pop up a warning to let user pay attention.
  419. #
  420. # eg. If current system has 2 physical CPUs with 16 cores each. And each core support 2
  421. # threads, then the total logical cpus here is 2 * 16 * 2 = 64. Let's say current
  422. # DataLoader process can use half of them which is 32, then the rational max number of
  423. # worker that initiated from this process is 32.
  424. # Now, let's say the created DataLoader has num_works = 40, which is bigger than 32.
  425. # So the warning message is triggered to notify the user to lower the worker number if
  426. # necessary.
  427. #
  428. #
  429. # [Note] Please note that this function repects `cpuset` only when os.sched_getaffinity is
  430. # available (available in most of Linux system, but not OSX and Windows).
  431. # When os.sched_getaffinity is not available, os.cpu_count() is called instead, but
  432. # it doesn't repect cpuset.
  433. # We don't take threading into account since each worker process is single threaded
  434. # at this time.
  435. #
  436. # We don't set any threading flags (eg. OMP_NUM_THREADS, MKL_NUM_THREADS, etc)
  437. # other than `torch.set_num_threads` to 1 in the worker process, if the passing
  438. # in functions use 3rd party modules that rely on those threading flags to determine
  439. # how many thread to create (eg. numpy, etc), then it is caller's responsibility to
  440. # set those flags correctly.
  441. def _create_warning_msg(num_worker_suggest, num_worker_created, cpuset_checked):
  442. suggested_max_worker_msg = ((
  443. "Our suggested max number of worker in current system is {}{}, which is smaller "
  444. "than what this DataLoader is going to create.").format(
  445. num_worker_suggest,
  446. ("" if cpuset_checked else " (`cpuset` is not taken into account)"))
  447. ) if num_worker_suggest is not None else (
  448. "DataLoader is not able to compute a suggested max number of worker in current system.")
  449. warn_msg = (
  450. "This DataLoader will create {} worker processes in total. {} "
  451. "Please be aware that excessive worker creation might get DataLoader running slow or even freeze, "
  452. "lower the worker number to avoid potential slowness/freeze if necessary.").format(
  453. num_worker_created,
  454. suggested_max_worker_msg)
  455. return warn_msg
  456. if not self.num_workers or self.num_workers == 0:
  457. return
  458. # try to compute a suggested max number of worker based on system's resource
  459. max_num_worker_suggest = None
  460. cpuset_checked = False
  461. if hasattr(os, 'sched_getaffinity'):
  462. try:
  463. max_num_worker_suggest = len(os.sched_getaffinity(0))
  464. cpuset_checked = True
  465. except Exception:
  466. pass
  467. if max_num_worker_suggest is None:
  468. # os.cpu_count() could return Optional[int]
  469. # get cpu count first and check None in order to satify mypy check
  470. cpu_count = os.cpu_count()
  471. if cpu_count is not None:
  472. max_num_worker_suggest = cpu_count
  473. if max_num_worker_suggest is None:
  474. warnings.warn(_create_warning_msg(
  475. max_num_worker_suggest,
  476. self.num_workers,
  477. cpuset_checked))
  478. return
  479. if self.num_workers > max_num_worker_suggest:
  480. warnings.warn(_create_warning_msg(
  481. max_num_worker_suggest,
  482. self.num_workers,
  483. cpuset_checked))
  484. class _BaseDataLoaderIter:
  485. def __init__(self, loader: DataLoader) -> None:
  486. self._dataset = loader.dataset
  487. self._shared_seed = None
  488. self._pg = None
  489. if isinstance(self._dataset, IterDataPipe):
  490. if dist.is_available() and dist.is_initialized():
  491. self._pg = dist.new_group(backend="gloo")
  492. self._shared_seed = _share_dist_seed(loader.generator, self._pg)
  493. shared_rng = torch.Generator()
  494. shared_rng.manual_seed(self._shared_seed)
  495. self._dataset = torch.utils.data.graph_settings.apply_random_seed(self._dataset, shared_rng)
  496. self._dataset_kind = loader._dataset_kind
  497. self._IterableDataset_len_called = loader._IterableDataset_len_called
  498. self._auto_collation = loader._auto_collation
  499. self._drop_last = loader.drop_last
  500. self._index_sampler = loader._index_sampler
  501. self._num_workers = loader.num_workers
  502. ws, rank = _get_distributed_settings()
  503. self._world_size = ws
  504. self._rank = rank
  505. # for other backends, pin_memory_device need to set. if not set
  506. # default behaviour is CUDA device. if pin_memory_device is selected
  507. # and pin_memory is not set, the default behaviour false.
  508. if (len(loader.pin_memory_device) == 0):
  509. self._pin_memory = loader.pin_memory and torch.cuda.is_available()
  510. self._pin_memory_device = None
  511. else:
  512. if not loader.pin_memory:
  513. warn_msg = ("pin memory device is set and pin_memory flag is not used then device pinned memory won't be used"
  514. "please set pin_memory to true, if you need to use the device pin memory")
  515. warnings.warn(warn_msg)
  516. self._pin_memory = loader.pin_memory
  517. self._pin_memory_device = loader.pin_memory_device
  518. self._timeout = loader.timeout
  519. self._collate_fn = loader.collate_fn
  520. self._sampler_iter = iter(self._index_sampler)
  521. self._base_seed = torch.empty((), dtype=torch.int64).random_(generator=loader.generator).item()
  522. self._persistent_workers = loader.persistent_workers
  523. self._num_yielded = 0
  524. self._profile_name = "enumerate(DataLoader)#{}.__next__".format(self.__class__.__name__)
  525. def __iter__(self) -> '_BaseDataLoaderIter':
  526. return self
  527. def _reset(self, loader, first_iter=False):
  528. self._sampler_iter = iter(self._index_sampler)
  529. self._num_yielded = 0
  530. self._IterableDataset_len_called = loader._IterableDataset_len_called
  531. if isinstance(self._dataset, IterDataPipe):
  532. self._shared_seed = _share_dist_seed(loader.generator, self._pg)
  533. shared_rng = torch.Generator()
  534. shared_rng.manual_seed(self._shared_seed)
  535. self._dataset = torch.utils.data.graph_settings.apply_random_seed(self._dataset, shared_rng)
  536. def _next_index(self):
  537. return next(self._sampler_iter) # may raise StopIteration
  538. def _next_data(self):
  539. raise NotImplementedError
  540. def __next__(self) -> Any:
  541. with torch.autograd.profiler.record_function(self._profile_name):
  542. if self._sampler_iter is None:
  543. # TODO(https://github.com/pytorch/pytorch/issues/76750)
  544. self._reset() # type: ignore[call-arg]
  545. data = self._next_data()
  546. self._num_yielded += 1
  547. if self._dataset_kind == _DatasetKind.Iterable and \
  548. self._IterableDataset_len_called is not None and \
  549. self._num_yielded > self._IterableDataset_len_called:
  550. warn_msg = ("Length of IterableDataset {} was reported to be {} (when accessing len(dataloader)), but {} "
  551. "samples have been fetched. ").format(self._dataset, self._IterableDataset_len_called,
  552. self._num_yielded)
  553. if self._num_workers > 0:
  554. warn_msg += ("For multiprocessing data-loading, this could be caused by not properly configuring the "
  555. "IterableDataset replica at each worker. Please see "
  556. "https://pytorch.org/docs/stable/data.html#torch.utils.data.IterableDataset for examples.")
  557. warnings.warn(warn_msg)
  558. return data
  559. def __len__(self) -> int:
  560. return len(self._index_sampler)
  561. def __getstate__(self):
  562. # TODO: add limited pickling support for sharing an iterator
  563. # across multiple threads for HOGWILD.
  564. # Probably the best way to do this is by moving the sample pushing
  565. # to a separate thread and then just sharing the data queue
  566. # but signalling the end is tricky without a non-blocking API
  567. raise NotImplementedError("{} cannot be pickled", self.__class__.__name__)
  568. class _SingleProcessDataLoaderIter(_BaseDataLoaderIter):
  569. def __init__(self, loader):
  570. super().__init__(loader)
  571. assert self._timeout == 0
  572. assert self._num_workers == 0
  573. # Adds forward compatibilities so classic DataLoader can work with DataPipes:
  574. # Taking care of distributed sharding
  575. if isinstance(self._dataset, (IterDataPipe, MapDataPipe)):
  576. torch.utils.data.graph_settings.apply_sharding(
  577. self._dataset, self._world_size, self._rank, sharding_group=SHARDING_PRIORITIES.DISTRIBUTED)
  578. self._dataset_fetcher = _DatasetKind.create_fetcher(
  579. self._dataset_kind, self._dataset, self._auto_collation, self._collate_fn, self._drop_last)
  580. def _next_data(self):
  581. index = self._next_index() # may raise StopIteration
  582. data = self._dataset_fetcher.fetch(index) # may raise StopIteration
  583. if self._pin_memory:
  584. data = _utils.pin_memory.pin_memory(data, self._pin_memory_device)
  585. return data
  586. class _MultiProcessingDataLoaderIter(_BaseDataLoaderIter):
  587. r"""Iterates once over the DataLoader's dataset, as specified by the sampler"""
  588. # NOTE [ Data Loader Multiprocessing Shutdown Logic ]
  589. #
  590. # Preliminary:
  591. #
  592. # Our data model looks like this (queues are indicated with curly brackets):
  593. #
  594. # main process ||
  595. # | ||
  596. # {index_queue} ||
  597. # | ||
  598. # worker processes || DATA
  599. # | ||
  600. # {worker_result_queue} || FLOW
  601. # | ||
  602. # pin_memory_thread of main process || DIRECTION
  603. # | ||
  604. # {data_queue} ||
  605. # | ||
  606. # data output \/
  607. #
  608. # P.S. `worker_result_queue` and `pin_memory_thread` part may be omitted if
  609. # `pin_memory=False`.
  610. #
  611. #
  612. # Terminating multiprocessing logic requires very careful design. In
  613. # particular, we need to make sure that
  614. #
  615. # 1. The iterator gracefully exits the workers when its last reference is
  616. # gone or it is depleted.
  617. #
  618. # In this case, the workers should be gracefully exited because the
  619. # main process may still need to continue to run, and we want cleaning
  620. # up code in the workers to be executed (e.g., releasing GPU memory).
  621. # Naturally, we implement the shutdown logic in `__del__` of
  622. # DataLoaderIterator.
  623. #
  624. # We delay the discussion on the logic in this case until later.
  625. #
  626. # 2. The iterator exits the workers when the loader process and/or worker
  627. # processes exits normally or with error.
  628. #
  629. # We set all workers and `pin_memory_thread` to have `daemon=True`.
  630. #
  631. # You may ask, why can't we make the workers non-daemonic, and
  632. # gracefully exit using the same logic as we have in `__del__` when the
  633. # iterator gets deleted (see 1 above)?
  634. #
  635. # First of all, `__del__` is **not** guaranteed to be called when
  636. # interpreter exits. Even if it is called, by the time it executes,
  637. # many Python core library resources may alreay be freed, and even
  638. # simple things like acquiring an internal lock of a queue may hang.
  639. # Therefore, in this case, we actually need to prevent `__del__` from
  640. # being executed, and rely on the automatic termination of daemonic
  641. # children.
  642. #
  643. # Thus, we register an `atexit` hook that sets a global flag
  644. # `_utils.python_exit_status`. Since `atexit` hooks are executed in the
  645. # reverse order of registration, we are guaranteed that this flag is
  646. # set before library resources we use are freed (which, at least in
  647. # CPython, is done via an `atexit` handler defined in
  648. # `multiprocessing/util.py`
  649. # https://github.com/python/cpython/blob/c606624af8d4cb3b4a052fb263bb983b3f87585b/Lib/multiprocessing/util.py#L320-L362
  650. # registered when an object requiring this mechanism is first
  651. # created, e.g., `mp.Queue`
  652. # https://github.com/python/cpython/blob/c606624af8d4cb3b4a052fb263bb983b3f87585b/Lib/multiprocessing/context.py#L100-L103
  653. # https://github.com/python/cpython/blob/c606624af8d4cb3b4a052fb263bb983b3f87585b/Lib/multiprocessing/queues.py#L29
  654. # )
  655. #
  656. # So in `__del__`, we check if `_utils.python_exit_status` is set or
  657. # `None` (freed), and perform no-op if so.
  658. #
  659. # However, simply letting library clean-up codes run can also be bad,
  660. # because such codes (i.e., `multiprocessing.util._exit_function()`)
  661. # include join putting threads for `mp.Queue`, which can be blocking.
  662. # Hence, the main process putting threads are called with
  663. # `cancel_join_thread` at creation. See later section
  664. # [ 3b. A process won't hang when putting into a queue; ]
  665. # for more details.
  666. #
  667. # Here are two example cases where library clean-up codes can run
  668. # before `__del__` is called:
  669. #
  670. # 1. If we hold onto a reference to the iterator, it more often
  671. # than not tries to do `multiprocessing` library cleaning before
  672. # clearing the alive referenced objects (https://github.com/pytorch/pytorch/issues/48666)
  673. # and thus prevents our cleaning-up code to run first.
  674. #
  675. # 2. A similar issue araises when a `DataLoader` is used in a subprocess.
  676. # When a process ends, it shuts the all its daemonic children
  677. # down with a SIGTERM (instead of joining them without a timeout).
  678. # Simiarly for threads, but by a different mechanism. This fact,
  679. # together with a few implementation details of multiprocessing, forces
  680. # us to make workers daemonic. All of our problems arise when a
  681. # DataLoader is used in a subprocess, and are caused by multiprocessing
  682. # code which looks more or less like this:
  683. #
  684. # try:
  685. # your_function_using_a_dataloader()
  686. # finally:
  687. # multiprocessing.util._exit_function()
  688. #
  689. # The joining/termination mentioned above happens inside
  690. # `_exit_function()`. Now, if `your_function_using_a_dataloader()`
  691. # throws, the stack trace stored in the exception will prevent the
  692. # frame which uses `DataLoaderIter` to be freed. If the frame has any
  693. # reference to the `DataLoaderIter` (e.g., in a method of the iter),
  694. # its `__del__`, which starts the shutdown procedure, will not be
  695. # called. That, in turn, means that workers aren't notified. Attempting
  696. # to join in `_exit_function` will then result in a hang.
  697. #
  698. # For context, `_exit_function` is also registered as an `atexit` call.
  699. # So it is unclear to me (@ssnl) why this is needed in a finally block.
  700. # The code dates back to 2008 and there is no comment on the original
  701. # PEP 371 or patch https://bugs.python.org/issue3050 (containing both
  702. # the finally block and the `atexit` registration) that explains this.
  703. #
  704. #
  705. # Finally, another choice is to just shutdown workers with logic in 1
  706. # above whenever we see an error in `next`. This isn't ideal because
  707. # a. It prevents users from using try-catch to resume data loading.
  708. # b. It doesn't prevent hanging if users have references to the
  709. # iterator.
  710. #
  711. # 3. All processes exit if any of them die unexpectedly by fatal signals.
  712. #
  713. # As shown above, the workers are set as daemonic children of the main
  714. # process. However, automatic cleaning-up of such child processes only
  715. # happens if the parent process exits gracefully (e.g., not via fatal
  716. # signals like SIGKILL). So we must ensure that each process will exit
  717. # even the process that should send/receive data to/from it were
  718. # killed, i.e.,
  719. #
  720. # a. A process won't hang when getting from a queue.
  721. #
  722. # Even with carefully designed data dependencies (i.e., a `put()`
  723. # always corresponding to a `get()`), hanging on `get()` can still
  724. # happen when data in queue is corrupted (e.g., due to
  725. # `cancel_join_thread` or unexpected exit).
  726. #
  727. # For child exit, we set a timeout whenever we try to get data
  728. # from `data_queue`, and check the workers' status on each timeout
  729. # and error.
  730. # See `_DataLoaderiter._get_batch()` and
  731. # `_DataLoaderiter._try_get_data()` for details.
  732. #
  733. # Additionally, for child exit on non-Windows platforms, we also
  734. # register a SIGCHLD handler (which is supported on Windows) on
  735. # the main process, which checks if any of the workers fail in the
  736. # (Python) handler. This is more efficient and faster in detecting
  737. # worker failures, compared to only using the above mechanism.
  738. # See `DataLoader.cpp` and `_utils/signal_handling.py` for details.
  739. #
  740. # For `.get()` calls where the sender(s) is not the workers, we
  741. # guard them with timeouts, and check the status of the sender
  742. # when timeout happens:
  743. # + in the workers, the `_utils.worker.ManagerWatchdog` class
  744. # checks the status of the main process.
  745. # + if `pin_memory=True`, when getting from `pin_memory_thread`,
  746. # check `pin_memory_thread` status periodically until `.get()`
  747. # returns or see that `pin_memory_thread` died.
  748. #
  749. # b. A process won't hang when putting into a queue;
  750. #
  751. # We use `mp.Queue` which has a separate background thread to put
  752. # objects from an unbounded buffer array. The background thread is
  753. # daemonic and usually automatically joined when the process
  754. # *exits*.
  755. #
  756. # In case that the receiver has ended abruptly while
  757. # reading from the pipe, the join will hang forever. The usual
  758. # solution for this in Python is calling `q.cancel_join_thread`,
  759. # which prevents automatically joining it when finalizing
  760. # (exiting).
  761. #
  762. # Nonetheless, `cancel_join_thread` must only be called when the
  763. # queue is **not** going to be read from or write into by another
  764. # process, because it may hold onto a lock or leave corrupted data
  765. # in the queue, leading other readers/writers to hang.
  766. #
  767. # Hence,
  768. # + For worker processes, we only do so (for their output
  769. # queues, i.e., `worker_result_queue`) before exiting.
  770. # + For `pin_memory_thread`, its output queue `data_queue` is a
  771. # `queue.Queue` that does blocking `put` if the queue is full.
  772. # So there is no above problem, but as a result, in
  773. # `_pin_memory_loop`, we do need to wrap the `put` in a loop
  774. # that breaks not only upon success, but also when the main
  775. # process stops reading, i.e., is shutting down.
  776. # + For loader process, we `cancel_join_thread()` for all
  777. # `_index_queues` because the whole purpose of workers and
  778. # `pin_memory_thread` is to serve the loader process. If
  779. # loader process is already exiting, we don't really care if
  780. # the queues are corrupted.
  781. #
  782. #
  783. # Now let's get back to 1:
  784. # how we gracefully exit the workers when the last reference to the
  785. # iterator is gone.
  786. #
  787. # To achieve this, we implement the following logic along with the design
  788. # choices mentioned above:
  789. #
  790. # `workers_done_event`:
  791. # A `multiprocessing.Event` shared among the main process and all worker
  792. # processes. This is used to signal the workers that the iterator is
  793. # shutting down. After it is set, they will not send processed data to
  794. # queues anymore, and only wait for the final `None` before exiting.
  795. # `done_event` isn't strictly needed. I.e., we can just check for `None`
  796. # from the input queue, but it allows us to skip wasting resources
  797. # processing data if we are already shutting down.
  798. #
  799. # `pin_memory_thread_done_event`:
  800. # A `threading.Event` for a similar purpose to that of
  801. # `workers_done_event`, but is for the `pin_memory_thread`. The reason
  802. # that separate events are needed is that `pin_memory_thread` reads from
  803. # the output queue of the workers. But the workers, upon seeing that
  804. # `workers_done_event` is set, only wants to see the final `None`, and is
  805. # not required to flush all data in the output queue (e.g., it may call
  806. # `cancel_join_thread` on that queue if its `IterableDataset` iterator
  807. # happens to exhaust coincidentally, which is out of the control of the
  808. # main process). Thus, since we will exit `pin_memory_thread` before the
  809. # workers (see below), two separete events are used.
  810. #
  811. # NOTE: In short, the protocol is that the main process will set these
  812. # `done_event`s and then the corresponding processes/threads a `None`,
  813. # and that they may exit at any time after receiving the `None`.
  814. #
  815. # NOTE: Using `None` as the final signal is valid, since normal data will
  816. # always be a 2-tuple with the 1st element being the index of the data
  817. # transferred (different from dataset index/key), and the 2nd being
  818. # either the dataset key or the data sample (depending on which part
  819. # of the data model the queue is at).
  820. #
  821. # [ worker processes ]
  822. # While loader process is alive:
  823. # Get from `index_queue`.
  824. # If get anything else,
  825. # Check `workers_done_event`.
  826. # If set, continue to next iteration
  827. # i.e., keep getting until see the `None`, then exit.
  828. # Otherwise, process data:
  829. # If is fetching from an `IterableDataset` and the iterator
  830. # is exhausted, send an `_IterableDatasetStopIteration`
  831. # object to signal iteration end. The main process, upon
  832. # receiving such an object, will send `None` to this
  833. # worker and not use the corresponding `index_queue`
  834. # anymore.
  835. # If timed out,
  836. # No matter `workers_done_event` is set (still need to see `None`)
  837. # or not, must continue to next iteration.
  838. # (outside loop)
  839. # If `workers_done_event` is set, (this can be False with `IterableDataset`)
  840. # `data_queue.cancel_join_thread()`. (Everything is ending here:
  841. # main process won't read from it;
  842. # other workers will also call
  843. # `cancel_join_thread`.)
  844. #
  845. # [ pin_memory_thread ]
  846. # # No need to check main thread. If this thread is alive, the main loader
  847. # # thread must be alive, because this thread is set as daemonic.
  848. # While `pin_memory_thread_done_event` is not set:
  849. # Get from `index_queue`.
  850. # If timed out, continue to get in the next iteration.
  851. # Otherwise, process data.
  852. # While `pin_memory_thread_done_event` is not set:
  853. # Put processed data to `data_queue` (a `queue.Queue` with blocking put)
  854. # If timed out, continue to put in the next iteration.
  855. # Otherwise, break, i.e., continuing to the out loop.
  856. #
  857. # NOTE: we don't check the status of the main thread because
  858. # 1. if the process is killed by fatal signal, `pin_memory_thread`
  859. # ends.
  860. # 2. in other cases, either the cleaning-up in __del__ or the
  861. # automatic exit of daemonic thread will take care of it.
  862. # This won't busy-wait either because `.get(timeout)` does not
  863. # busy-wait.
  864. #
  865. # [ main process ]
  866. # In the DataLoader Iter's `__del__`
  867. # b. Exit `pin_memory_thread`
  868. # i. Set `pin_memory_thread_done_event`.
  869. # ii Put `None` in `worker_result_queue`.
  870. # iii. Join the `pin_memory_thread`.
  871. # iv. `worker_result_queue.cancel_join_thread()`.
  872. #
  873. # c. Exit the workers.
  874. # i. Set `workers_done_event`.
  875. # ii. Put `None` in each worker's `index_queue`.
  876. # iii. Join the workers.
  877. # iv. Call `.cancel_join_thread()` on each worker's `index_queue`.
  878. #
  879. # NOTE: (c) is better placed after (b) because it may leave corrupted
  880. # data in `worker_result_queue`, which `pin_memory_thread`
  881. # reads from, in which case the `pin_memory_thread` can only
  882. # happen at timeing out, which is slow. Nonetheless, same thing
  883. # happens if a worker is killed by signal at unfortunate times,
  884. # but in other cases, we are better off having a non-corrupted
  885. # `worker_result_queue` for `pin_memory_thread`.
  886. #
  887. # NOTE: If `pin_memory=False`, there is no `pin_memory_thread` and (b)
  888. # can be omitted
  889. #
  890. # NB: `done_event`s isn't strictly needed. E.g., we can just check for
  891. # `None` from `index_queue`, but it allows us to skip wasting resources
  892. # processing indices already in `index_queue` if we are already shutting
  893. # down.
  894. def __init__(self, loader):
  895. super().__init__(loader)
  896. self._prefetch_factor = loader.prefetch_factor
  897. assert self._num_workers > 0
  898. assert self._prefetch_factor > 0
  899. if loader.multiprocessing_context is None:
  900. multiprocessing_context = multiprocessing
  901. else:
  902. multiprocessing_context = loader.multiprocessing_context
  903. self._worker_init_fn = loader.worker_init_fn
  904. # Adds forward compatibilities so classic DataLoader can work with DataPipes:
  905. # Additional worker init function will take care of sharding in MP and Distributed
  906. if isinstance(self._dataset, (IterDataPipe, MapDataPipe)):
  907. self._worker_init_fn = functools.partial(
  908. _sharding_worker_init_fn, self._worker_init_fn, self._world_size, self._rank)
  909. # No certainty which module multiprocessing_context is
  910. self._worker_result_queue = multiprocessing_context.Queue() # type: ignore[var-annotated]
  911. self._worker_pids_set = False
  912. self._shutdown = False
  913. self._workers_done_event = multiprocessing_context.Event()
  914. self._index_queues = []
  915. self._workers = []
  916. for i in range(self._num_workers):
  917. # No certainty which module multiprocessing_context is
  918. index_queue = multiprocessing_context.Queue() # type: ignore[var-annotated]
  919. # Need to `cancel_join_thread` here!
  920. # See sections (2) and (3b) above.
  921. index_queue.cancel_join_thread()
  922. w = multiprocessing_context.Process(
  923. target=_utils.worker._worker_loop,
  924. args=(self._dataset_kind, self._dataset, index_queue,
  925. self._worker_result_queue, self._workers_done_event,
  926. self._auto_collation, self._collate_fn, self._drop_last,
  927. self._base_seed, self._worker_init_fn, i, self._num_workers,
  928. self._persistent_workers, self._shared_seed))
  929. w.daemon = True
  930. # NB: Process.start() actually take some time as it needs to
  931. # start a process and pass the arguments over via a pipe.
  932. # Therefore, we only add a worker to self._workers list after
  933. # it started, so that we do not call .join() if program dies
  934. # before it starts, and __del__ tries to join but will get:
  935. # AssertionError: can only join a started process.
  936. w.start()
  937. self._index_queues.append(index_queue)
  938. self._workers.append(w)
  939. if self._pin_memory:
  940. self._pin_memory_thread_done_event = threading.Event()
  941. # Queue is not type-annotated
  942. self._data_queue = queue.Queue() # type: ignore[var-annotated]
  943. if self._pin_memory_device == "xpu":
  944. current_device = torch.xpu.current_device() # type: ignore[attr-defined]
  945. else:
  946. current_device = torch.cuda.current_device() # choose cuda for default
  947. pin_memory_thread = threading.Thread(
  948. target=_utils.pin_memory._pin_memory_loop,
  949. args=(self._worker_result_queue, self._data_queue,
  950. current_device,
  951. self._pin_memory_thread_done_event, self._pin_memory_device))
  952. pin_memory_thread.daemon = True
  953. pin_memory_thread.start()
  954. # Similar to workers (see comment above), we only register
  955. # pin_memory_thread once it is started.
  956. self._pin_memory_thread = pin_memory_thread
  957. else:
  958. self._data_queue = self._worker_result_queue
  959. # In some rare cases, persistent workers (daemonic processes)
  960. # would be terminated before `__del__` of iterator is invoked
  961. # when main process exits
  962. # It would cause failure when pin_memory_thread tries to read
  963. # corrupted data from worker_result_queue
  964. # atexit is used to shutdown thread and child processes in the
  965. # right sequence before main process exits
  966. if self._persistent_workers and self._pin_memory:
  967. import atexit
  968. for w in self._workers:
  969. atexit.register(_MultiProcessingDataLoaderIter._clean_up_worker, w)
  970. # .pid can be None only before process is spawned (not the case, so ignore)
  971. _utils.signal_handling._set_worker_pids(id(self), tuple(w.pid for w in self._workers)) # type: ignore[misc]
  972. _utils.signal_handling._set_SIGCHLD_handler()
  973. self._worker_pids_set = True
  974. self._reset(loader, first_iter=True)
  975. def _reset(self, loader, first_iter=False):
  976. super()._reset(loader, first_iter)
  977. self._send_idx = 0 # idx of the next task to be sent to workers
  978. self._rcvd_idx = 0 # idx of the next task to be returned in __next__
  979. # information about data not yet yielded, i.e., tasks w/ indices in range [rcvd_idx, send_idx).
  980. # map: task idx => - (worker_id,) if data isn't fetched (outstanding)
  981. # \ (worker_id, data) if data is already fetched (out-of-order)
  982. self._task_info = {}
  983. self._tasks_outstanding = 0 # always equal to count(v for v in task_info.values() if len(v) == 1)
  984. # A list of booleans representing whether each worker still has work to
  985. # do, i.e., not having exhausted its iterable dataset object. It always
  986. # contains all `True`s if not using an iterable-style dataset
  987. # (i.e., if kind != Iterable).
  988. # Not that this indicates that a worker still has work to do *for this epoch*.
  989. # It does not mean that a worker is dead. In case of `_persistent_workers`,
  990. # the worker will be reset to available in the next epoch.
  991. self._workers_status = [True for i in range(self._num_workers)]
  992. # Reset the worker queue cycle so it resumes next epoch at worker 0
  993. self._worker_queue_idx_cycle = itertools.cycle(range(self._num_workers))
  994. # We resume the prefetching in case it was enabled
  995. if not first_iter:
  996. for idx in range(self._num_workers):
  997. self._index_queues[idx].put(_utils.worker._ResumeIteration(self._shared_seed))
  998. resume_iteration_cnt = self._num_workers
  999. while resume_iteration_cnt > 0:
  1000. return_idx, return_data = self._get_data()
  1001. if isinstance(return_idx, _utils.worker._ResumeIteration):
  1002. assert return_data is None
  1003. resume_iteration_cnt -= 1
  1004. # prime the prefetch loop
  1005. for _ in range(self._prefetch_factor * self._num_workers):
  1006. self._try_put_index()
  1007. def _try_get_data(self, timeout=_utils.MP_STATUS_CHECK_INTERVAL):
  1008. # Tries to fetch data from `self._data_queue` once for a given timeout.
  1009. # This can also be used as inner loop of fetching without timeout, with
  1010. # the sender status as the loop condition.
  1011. #
  1012. # This raises a `RuntimeError` if any worker died expectedly. This error
  1013. # can come from either the SIGCHLD handler in `_utils/signal_handling.py`
  1014. # (only for non-Windows platforms), or the manual check below on errors
  1015. # and timeouts.
  1016. #
  1017. # Returns a 2-tuple:
  1018. # (bool: whether successfully get data, any: data if successful else None)
  1019. try:
  1020. data = self._data_queue.get(timeout=timeout)
  1021. return (True, data)
  1022. except Exception as e:
  1023. # At timeout and error, we manually check whether any worker has
  1024. # failed. Note that this is the only mechanism for Windows to detect
  1025. # worker failures.
  1026. failed_workers = []
  1027. for worker_id, w in enumerate(self._workers):
  1028. if self._workers_status[worker_id] and not w.is_alive():
  1029. failed_workers.append(w)
  1030. self._mark_worker_as_unavailable(worker_id)
  1031. if len(failed_workers) > 0:
  1032. pids_str = ', '.join(str(w.pid) for w in failed_workers)
  1033. raise RuntimeError('DataLoader worker (pid(s) {}) exited unexpectedly'.format(pids_str)) from e
  1034. if isinstance(e, queue.Empty):
  1035. return (False, None)
  1036. import tempfile
  1037. import errno
  1038. try:
  1039. # Raise an exception if we are this close to the FDs limit.
  1040. # Apparently, trying to open only one file is not a sufficient
  1041. # test.
  1042. # See NOTE [ DataLoader on Linux and open files limit ]
  1043. fds_limit_margin = 10
  1044. fs = [tempfile.NamedTemporaryFile() for i in range(fds_limit_margin)]
  1045. except OSError as e:
  1046. if e.errno == errno.EMFILE:
  1047. raise RuntimeError(
  1048. "Too many open files. Communication with the"
  1049. " workers is no longer possible. Please increase the"
  1050. " limit using `ulimit -n` in the shell or change the"
  1051. " sharing strategy by calling"
  1052. " `torch.multiprocessing.set_sharing_strategy('file_system')`"
  1053. " at the beginning of your code") from None
  1054. raise
  1055. # NOTE [ DataLoader on Linux and open files limit ]
  1056. #
  1057. # On Linux when DataLoader is used with multiprocessing we pass the data between
  1058. # the root process and the workers through SHM files. We remove those files from
  1059. # the filesystem as soon as they are created and keep them alive by
  1060. # passing around their file descriptors through AF_UNIX sockets. (See
  1061. # docs/source/multiprocessing.rst and 'Multiprocessing Technical Notes` in
  1062. # the wiki (https://github.com/pytorch/pytorch/wiki).)
  1063. #
  1064. # This sometimes leads us to exceeding the open files limit. When that happens,
  1065. # and the offending file descriptor is coming over a socket, the `socket` Python
  1066. # package silently strips the file descriptor from the message, setting only the
  1067. # `MSG_CTRUNC` flag (which might be a bit misleading since the manpage says that
  1068. # it _indicates that some control data were discarded due to lack of space in
  1069. # the buffer for ancillary data_). This might reflect the C implementation of
  1070. # AF_UNIX sockets.
  1071. #
  1072. # This behaviour can be reproduced with the script and instructions at the
  1073. # bottom of this note.
  1074. #
  1075. # When that happens, the standard Python `multiprocessing` (and not
  1076. # `torch.multiprocessing`) raises a `RuntimeError: received 0 items of ancdata`
  1077. #
  1078. # Sometimes, instead of the FD being stripped, you may get an `OSError:
  1079. # Too many open files`, both in the script below and in DataLoader. However,
  1080. # this is rare and seems to be nondeterministic.
  1081. #
  1082. #
  1083. # #!/usr/bin/env python3
  1084. # import sys
  1085. # import socket
  1086. # import os
  1087. # import array
  1088. # import shutil
  1089. # import socket
  1090. #
  1091. #
  1092. # if len(sys.argv) != 4:
  1093. # print("Usage: ", sys.argv[0], " tmp_dirname iteration (send|recv)")
  1094. # sys.exit(1)
  1095. #
  1096. # if __name__ == '__main__':
  1097. # dirname = sys.argv[1]
  1098. # sock_path = dirname + "/sock"
  1099. # iterations = int(sys.argv[2])
  1100. # def dummy_path(i):
  1101. # return dirname + "/" + str(i) + ".dummy"
  1102. #
  1103. #
  1104. # if sys.argv[3] == 'send':
  1105. # while not os.path.exists(sock_path):
  1106. # pass
  1107. # client = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
  1108. # client.connect(sock_path)
  1109. # for i in range(iterations):
  1110. # fd = os.open(dummy_path(i), os.O_WRONLY | os.O_CREAT)
  1111. # ancdata = array.array('i', [fd])
  1112. # msg = bytes([i % 256])
  1113. # print("Sending fd ", fd, " (iteration #", i, ")")
  1114. # client.sendmsg([msg], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, ancdata)])
  1115. #
  1116. #
  1117. # else:
  1118. # assert sys.argv[3] == 'recv'
  1119. #
  1120. # if os.path.exists(dirname):
  1121. # raise Exception("Directory exists")
  1122. #
  1123. # os.mkdir(dirname)
  1124. #
  1125. # print("Opening socket...")
  1126. # server = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
  1127. # server.bind(sock_path)
  1128. #
  1129. # print("Listening...")
  1130. # for i in range(iterations):
  1131. # a = array.array('i')
  1132. # msg, ancdata, flags, addr = server.recvmsg(1, socket.CMSG_SPACE(a.itemsize))
  1133. # assert(len(ancdata) == 1)
  1134. # cmsg_level, cmsg_type, cmsg_data = ancdata[0]
  1135. # a.frombytes(cmsg_data)
  1136. # print("Received fd ", a[0], " (iteration #", i, ")")
  1137. #
  1138. # shutil.rmtree(dirname)
  1139. #
  1140. # Steps to reproduce:
  1141. #
  1142. # 1. Run two shells and set lower file descriptor limit in the receiving one:
  1143. # (shell1) ulimit -n 1020
  1144. # (shell2) ulimit -n 1022
  1145. #
  1146. # 2. Run the script above with the `recv` option in the first shell
  1147. # (shell1) ./test_socket.py sock_tmp 1017 recv
  1148. #
  1149. # 3. Run the script with the `send` option in the second shell:
  1150. # (shell2) ./test_socket.py sock_tmp 1017 send
  1151. def _get_data(self):
  1152. # Fetches data from `self._data_queue`.
  1153. #
  1154. # We check workers' status every `MP_STATUS_CHECK_INTERVAL` seconds,
  1155. # which we achieve by running `self._try_get_data(timeout=MP_STATUS_CHECK_INTERVAL)`
  1156. # in a loop. This is the only mechanism to detect worker failures for
  1157. # Windows. For other platforms, a SIGCHLD handler is also used for
  1158. # worker failure detection.
  1159. #
  1160. # If `pin_memory=True`, we also need check if `pin_memory_thread` had
  1161. # died at timeouts.
  1162. if self._timeout > 0:
  1163. success, data = self._try_get_data(self._timeout)
  1164. if success:
  1165. return data
  1166. else:
  1167. raise RuntimeError('DataLoader timed out after {} seconds'.format(self._timeout))
  1168. elif self._pin_memory:
  1169. while self._pin_memory_thread.is_alive():
  1170. success, data = self._try_get_data()
  1171. if success:
  1172. return data
  1173. else:
  1174. # while condition is false, i.e., pin_memory_thread died.
  1175. raise RuntimeError('Pin memory thread exited unexpectedly')
  1176. # In this case, `self._data_queue` is a `queue.Queue`,. But we don't
  1177. # need to call `.task_done()` because we don't use `.join()`.
  1178. else:
  1179. while True:
  1180. success, data = self._try_get_data()
  1181. if success:
  1182. return data
  1183. def _next_data(self):
  1184. while True:
  1185. # If the worker responsible for `self._rcvd_idx` has already ended
  1186. # and was unable to fulfill this task (due to exhausting an `IterableDataset`),
  1187. # we try to advance `self._rcvd_idx` to find the next valid index.
  1188. #
  1189. # This part needs to run in the loop because both the `self._get_data()`
  1190. # call and `_IterableDatasetStopIteration` check below can mark
  1191. # extra worker(s) as dead.
  1192. while self._rcvd_idx < self._send_idx:
  1193. info = self._task_info[self._rcvd_idx]
  1194. worker_id = info[0]
  1195. if len(info) == 2 or self._workers_status[worker_id]: # has data or is still active
  1196. break
  1197. del self._task_info[self._rcvd_idx]
  1198. self._rcvd_idx += 1
  1199. else:
  1200. # no valid `self._rcvd_idx` is found (i.e., didn't break)
  1201. if not self._persistent_workers:
  1202. self._shutdown_workers()
  1203. raise StopIteration
  1204. # Now `self._rcvd_idx` is the batch index we want to fetch
  1205. # Check if the next sample has already been generated
  1206. if len(self._task_info[self._rcvd_idx]) == 2:
  1207. data = self._task_info.pop(self._rcvd_idx)[1]
  1208. return self._process_data(data)
  1209. assert not self._shutdown and self._tasks_outstanding > 0
  1210. idx, data = self._get_data()
  1211. self._tasks_outstanding -= 1
  1212. if self._dataset_kind == _DatasetKind.Iterable:
  1213. # Check for _IterableDatasetStopIteration
  1214. if isinstance(data, _utils.worker._IterableDatasetStopIteration):
  1215. if self._persistent_workers:
  1216. self._workers_status[data.worker_id] = False
  1217. else:
  1218. self._mark_worker_as_unavailable(data.worker_id)
  1219. self._try_put_index()
  1220. continue
  1221. if idx != self._rcvd_idx:
  1222. # store out-of-order samples
  1223. self._task_info[idx] += (data,)
  1224. else:
  1225. del self._task_info[idx]
  1226. return self._process_data(data)
  1227. def _try_put_index(self):
  1228. assert self._tasks_outstanding < self._prefetch_factor * self._num_workers
  1229. try:
  1230. index = self._next_index()
  1231. except StopIteration:
  1232. return
  1233. for _ in range(self._num_workers): # find the next active worker, if any
  1234. worker_queue_idx = next(self._worker_queue_idx_cycle)
  1235. if self._workers_status[worker_queue_idx]:
  1236. break
  1237. else:
  1238. # not found (i.e., didn't break)
  1239. return
  1240. self._index_queues[worker_queue_idx].put((self._send_idx, index))
  1241. self._task_info[self._send_idx] = (worker_queue_idx,)
  1242. self._tasks_outstanding += 1
  1243. self._send_idx += 1
  1244. def _process_data(self, data):
  1245. self._rcvd_idx += 1
  1246. self._try_put_index()
  1247. if isinstance(data, ExceptionWrapper):
  1248. data.reraise()
  1249. return data
  1250. def _mark_worker_as_unavailable(self, worker_id, shutdown=False):
  1251. # Mark a worker as having finished its work e.g., due to
  1252. # exhausting an `IterableDataset`. This should be used only when this
  1253. # `_MultiProcessingDataLoaderIter` is going to continue running.
  1254. assert self._workers_status[worker_id] or (self._persistent_workers and shutdown)
  1255. # Signal termination to that specific worker.
  1256. q = self._index_queues[worker_id]
  1257. # Indicate that no more data will be put on this queue by the current
  1258. # process.
  1259. q.put(None)
  1260. # Note that we don't actually join the worker here, nor do we remove the
  1261. # worker's pid from C side struct because (1) joining may be slow, and
  1262. # (2) since we don't join, the worker may still raise error, and we
  1263. # prefer capturing those, rather than ignoring them, even though they
  1264. # are raised after the worker has finished its job.
  1265. # Joinning is deferred to `_shutdown_workers`, which it is called when
  1266. # all workers finish their jobs (e.g., `IterableDataset` replicas) or
  1267. # when this iterator is garbage collected.
  1268. self._workers_status[worker_id] = False
  1269. assert self._workers_done_event.is_set() == shutdown
  1270. def _shutdown_workers(self):
  1271. # Called when shutting down this `_MultiProcessingDataLoaderIter`.
  1272. # See NOTE [ Data Loader Multiprocessing Shutdown Logic ] for details on
  1273. # the logic of this function.
  1274. if _utils is None or _utils.python_exit_status is True or _utils.python_exit_status is None:
  1275. # See (2) of the note. If Python is shutting down, do no-op.
  1276. return
  1277. # Normal exit when last reference is gone / iterator is depleted.
  1278. # See (1) and the second half of the note.
  1279. if not self._shutdown:
  1280. self._shutdown = True
  1281. try:
  1282. # Normal exit when last reference is gone / iterator is depleted.
  1283. # See (1) and the second half of the note.
  1284. # Exit `pin_memory_thread` first because exiting workers may leave
  1285. # corrupted data in `worker_result_queue` which `pin_memory_thread`
  1286. # reads from.
  1287. if hasattr(self, '_pin_memory_thread'):
  1288. # Use hasattr in case error happens before we set the attribute.
  1289. self._pin_memory_thread_done_event.set()
  1290. # Send something to pin_memory_thread in case it is waiting
  1291. # so that it can wake up and check `pin_memory_thread_done_event`
  1292. self._worker_result_queue.put((None, None))
  1293. self._pin_memory_thread.join()
  1294. self._worker_result_queue.cancel_join_thread()
  1295. self._worker_result_queue.close()
  1296. # Exit workers now.
  1297. self._workers_done_event.set()
  1298. for worker_id in range(len(self._workers)):
  1299. # Get number of workers from `len(self._workers)` instead of
  1300. # `self._num_workers` in case we error before starting all
  1301. # workers.
  1302. # If we are using workers_status with persistent_workers
  1303. # we have to shut it down because the worker is paused
  1304. if self._persistent_workers or self._workers_status[worker_id]:
  1305. self._mark_worker_as_unavailable(worker_id, shutdown=True)
  1306. for w in self._workers:
  1307. # We should be able to join here, but in case anything went
  1308. # wrong, we set a timeout and if the workers fail to join,
  1309. # they are killed in the `finally` block.
  1310. w.join(timeout=_utils.MP_STATUS_CHECK_INTERVAL)
  1311. for q in self._index_queues:
  1312. q.cancel_join_thread()
  1313. q.close()
  1314. finally:
  1315. # Even though all this function does is putting into queues that
  1316. # we have called `cancel_join_thread` on, weird things can
  1317. # happen when a worker is killed by a signal, e.g., hanging in
  1318. # `Event.set()`. So we need to guard this with SIGCHLD handler,
  1319. # and remove pids from the C side data structure only at the
  1320. # end.
  1321. #
  1322. # FIXME: Unfortunately, for Windows, we are missing a worker
  1323. # error detection mechanism here in this function, as it
  1324. # doesn't provide a SIGCHLD handler.
  1325. if self._worker_pids_set:
  1326. _utils.signal_handling._remove_worker_pids(id(self))
  1327. self._worker_pids_set = False
  1328. for w in self._workers:
  1329. if w.is_alive():
  1330. # Existing mechanisms try to make the workers exit
  1331. # peacefully, but in case that we unfortunately reach
  1332. # here, which we shouldn't, (e.g., pytorch/pytorch#39570),
  1333. # we kill the worker.
  1334. w.terminate()
  1335. # staticmethod is used to remove reference to `_MultiProcessingDataLoaderIter`
  1336. @staticmethod
  1337. def _clean_up_worker(w):
  1338. try:
  1339. w.join(timeout=_utils.MP_STATUS_CHECK_INTERVAL)
  1340. finally:
  1341. if w.is_alive():
  1342. w.terminate()
  1343. def __del__(self):
  1344. self._shutdown_workers()