dataloader.py 72 KB

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