dataloader.py 77 KB

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