dataloader.py 75 KB

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