combining.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. # mypy: allow-untyped-defs
  2. import warnings
  3. from abc import ABC, abstractmethod
  4. from collections import deque
  5. import copy as copymodule
  6. from typing import Any, Callable, Iterator, List, Literal, Optional, Sized, Tuple, TypeVar, Deque
  7. from torch.utils.data.datapipes._decorator import functional_datapipe
  8. from torch.utils.data.datapipes._hook_iterator import _SnapshotState
  9. from torch.utils.data.datapipes.datapipe import IterDataPipe
  10. from torch.utils.data.datapipes.utils.common import StreamWrapper, _check_unpickable_fn
  11. __all__ = [
  12. "ConcaterIterDataPipe",
  13. "DemultiplexerIterDataPipe",
  14. "ForkerIterDataPipe",
  15. "MultiplexerIterDataPipe",
  16. "ZipperIterDataPipe",
  17. ]
  18. T_co = TypeVar('T_co', covariant=True)
  19. @functional_datapipe('concat')
  20. class ConcaterIterDataPipe(IterDataPipe):
  21. r"""
  22. Concatenates multiple Iterable DataPipes (functional name: ``concat``).
  23. The resulting DataPipe will yield all the elements from the first input DataPipe, before yielding from the subsequent ones.
  24. Args:
  25. datapipes: Iterable DataPipes being concatenated
  26. Example:
  27. >>> # xdoctest: +REQUIRES(module:torchdata)
  28. >>> import random
  29. >>> from torchdata.datapipes.iter import IterableWrapper
  30. >>> dp1 = IterableWrapper(range(3))
  31. >>> dp2 = IterableWrapper(range(5))
  32. >>> list(dp1.concat(dp2))
  33. [0, 1, 2, 0, 1, 2, 3, 4]
  34. """
  35. datapipes: Tuple[IterDataPipe]
  36. def __init__(self, *datapipes: IterDataPipe):
  37. if len(datapipes) == 0:
  38. raise ValueError("Expected at least one DataPipe, but got nothing")
  39. if not all(isinstance(dp, IterDataPipe) for dp in datapipes):
  40. raise TypeError("Expected all inputs to be `IterDataPipe`")
  41. self.datapipes = datapipes # type: ignore[assignment]
  42. def __iter__(self) -> Iterator:
  43. for dp in self.datapipes:
  44. yield from dp
  45. def __len__(self) -> int:
  46. if all(isinstance(dp, Sized) for dp in self.datapipes):
  47. return sum(len(dp) for dp in self.datapipes)
  48. else:
  49. raise TypeError(f"{type(self).__name__} instance doesn't have valid length")
  50. @functional_datapipe('fork')
  51. class ForkerIterDataPipe(IterDataPipe):
  52. r"""
  53. Creates multiple instances of the same Iterable DataPipe (functional name: ``fork``).
  54. Args:
  55. datapipe: Iterable DataPipe being copied
  56. num_instances: number of instances of the datapipe to create
  57. buffer_size: this restricts how far ahead the leading child DataPipe
  58. can read relative to the slowest child DataPipe.
  59. Defaults to ``1000``. Use ``-1`` for the unlimited buffer.
  60. copy: copy strategy to use for items yielded by each branch. Supported
  61. options are ``None`` for no copying, ``"shallow"`` for shallow object
  62. copies, and ``"deep"`` for deep object copies. Defaults to ``None``.
  63. Note:
  64. All branches of the forked pipeline return the identical object unless
  65. the copy parameter is supplied. If the object is mutable or contains
  66. mutable objects, changing them in one branch will affect all others.
  67. Example:
  68. >>> # xdoctest: +REQUIRES(module:torchdata)
  69. >>> from torchdata.datapipes.iter import IterableWrapper
  70. >>> source_dp = IterableWrapper(range(5))
  71. >>> dp1, dp2 = source_dp.fork(num_instances=2)
  72. >>> list(dp1)
  73. [0, 1, 2, 3, 4]
  74. >>> list(dp2)
  75. [0, 1, 2, 3, 4]
  76. """
  77. def __new__(
  78. cls,
  79. datapipe: IterDataPipe,
  80. num_instances: int,
  81. buffer_size: int = 1000,
  82. copy: Optional[Literal["shallow", "deep"]] = None
  83. ):
  84. if num_instances < 1:
  85. raise ValueError(f"Expected `num_instances` larger than 0, but {num_instances} is found")
  86. if num_instances == 1:
  87. return datapipe
  88. container = _ForkerIterDataPipe(datapipe, num_instances, buffer_size, copy) # type: ignore[abstract]
  89. return [_ChildDataPipe(container, i) for i in range(num_instances)]
  90. class _ContainerTemplate(ABC):
  91. r"""Abstract class for container ``DataPipes``. The followings are three required methods."""
  92. @abstractmethod
  93. def get_next_element_by_instance(self, instance_id: int):
  94. ...
  95. @abstractmethod
  96. def is_every_instance_exhausted(self) -> bool:
  97. ...
  98. @abstractmethod
  99. def reset(self) -> None:
  100. ...
  101. @abstractmethod
  102. def get_length_by_instance(self, instance_id: int):
  103. r"""Raise TypeError if it's not supposed to be implemented to support `list(datapipe)`."""
  104. def _no_op(x):
  105. return x
  106. class _ForkerIterDataPipe(IterDataPipe, _ContainerTemplate):
  107. r"""
  108. Container to hold instance-specific information on behalf of ForkerIterDataPipe.
  109. It tracks the state of its child DataPipes, maintains the buffer, and yields the next value
  110. as requested by the child DataPipes.
  111. """
  112. def __init__(
  113. self,
  114. datapipe: IterDataPipe,
  115. num_instances: int,
  116. buffer_size: int = 1000,
  117. copy: Optional[Literal["shallow", "deep"]] = None
  118. ):
  119. self.main_datapipe = datapipe
  120. self._datapipe_iterator: Optional[Iterator[Any]] = None
  121. self.num_instances = num_instances
  122. self.buffer: Deque = deque()
  123. self.buffer_size = buffer_size
  124. if self.buffer_size < 0:
  125. warnings.warn(
  126. "Unlimited buffer size is set for `fork`, "
  127. "please be aware of OOM at random places",
  128. UserWarning
  129. )
  130. if copy is None:
  131. self.copy_fn = _no_op
  132. elif copy == "shallow":
  133. self.copy_fn = copymodule.copy
  134. elif copy == "deep":
  135. self.copy_fn = copymodule.deepcopy
  136. else:
  137. raise ValueError(f"Unknown copy method `{copy}` requested, choose one of None, `shallow` or `deep`.")
  138. self.child_pointers: List[int] = [0] * num_instances # Indicate the indices of the next element to get
  139. self.slowest_ptr = 0 # The index to read by the slowest child
  140. self.leading_ptr = 0 # The index to read by the fastest child
  141. self.end_ptr: Optional[int] = None # The index to stop child
  142. self._child_stop: List[bool] = [True for _ in range(num_instances)]
  143. def __len__(self):
  144. return len(self.main_datapipe)
  145. def get_next_element_by_instance(self, instance_id: int):
  146. if self._datapipe_iterator is None and self._child_stop[instance_id]:
  147. self._datapipe_iterator = iter(self.main_datapipe)
  148. self._snapshot_state = _SnapshotState.Iterating
  149. for i in range(self.num_instances):
  150. self._child_stop[i] = False
  151. try:
  152. while not self._child_stop[instance_id]:
  153. self.child_pointers[instance_id] += 1
  154. if self.end_ptr is not None and self.child_pointers[instance_id] == self.end_ptr:
  155. self._child_stop[instance_id] = True
  156. break
  157. # Use buffer
  158. if self.buffer and self.child_pointers[instance_id] <= self.leading_ptr:
  159. idx = self.child_pointers[instance_id] - self.slowest_ptr - 1
  160. return_val = self.buffer[idx]
  161. else: # Retrieve one element from main datapipe
  162. self.leading_ptr = self.child_pointers[instance_id]
  163. try:
  164. return_val = next(self._datapipe_iterator) # type: ignore[arg-type]
  165. self.buffer.append(return_val)
  166. except StopIteration:
  167. self._child_stop[instance_id] = True
  168. self._datapipe_iterator = None
  169. self.end_ptr = self.leading_ptr
  170. continue
  171. if self.child_pointers[instance_id] == self.slowest_ptr + 1:
  172. new_min = min(self.child_pointers) # Can optimize by avoiding the call to min()
  173. if self.slowest_ptr < new_min:
  174. self.slowest_ptr = new_min
  175. self.buffer.popleft()
  176. if self.buffer_size >= 0 and self.leading_ptr > self.buffer_size + self.slowest_ptr:
  177. raise BufferError("ForkerIterDataPipe buffer overflow," +
  178. f"buffer size {self.buffer_size} is insufficient.")
  179. yield self.copy_fn(return_val) # type: ignore[possibly-undefined]
  180. finally:
  181. self._child_stop[instance_id] = True
  182. # Cleanup _datapipe_iterator for the case that fork exits earlier
  183. if all(self._child_stop):
  184. self._datapipe_iterator = None
  185. self._cleanup()
  186. def is_every_instance_exhausted(self) -> bool:
  187. return self.end_ptr is not None and all(self._child_stop)
  188. def get_length_by_instance(self, instance_id: int) -> int:
  189. return len(self.main_datapipe)
  190. def reset(self) -> None:
  191. self._datapipe_iterator = None
  192. self.buffer = deque()
  193. self.child_pointers = [0] * self.num_instances
  194. self.slowest_ptr = 0
  195. self.leading_ptr = 0
  196. self.end_ptr = None
  197. self._child_stop = [True for _ in range(self.num_instances)]
  198. def __getstate__(self):
  199. state = (
  200. self.main_datapipe,
  201. self.num_instances,
  202. self.buffer_size,
  203. self.copy_fn,
  204. self._valid_iterator_id,
  205. self._number_of_samples_yielded,
  206. )
  207. if IterDataPipe.getstate_hook is not None:
  208. return IterDataPipe.getstate_hook(state)
  209. return state
  210. def __setstate__(self, state):
  211. (
  212. self.main_datapipe,
  213. self.num_instances,
  214. self.buffer_size,
  215. self.copy_fn,
  216. self._valid_iterator_id,
  217. self._number_of_samples_yielded,
  218. ) = state
  219. self._datapipe_iterator = None
  220. self.buffer = deque()
  221. self.child_pointers = [0] * self.num_instances
  222. self.slowest_ptr = 0
  223. self.leading_ptr = 0
  224. self.end_ptr = None
  225. self._child_stop = [True for _ in range(self.num_instances)]
  226. def _cleanup(self):
  227. while self.buffer:
  228. d = self.buffer.popleft()
  229. StreamWrapper.close_streams(d)
  230. def __del__(self):
  231. self._cleanup()
  232. class _ChildDataPipe(IterDataPipe):
  233. r"""
  234. Iterable Datapipe that is a child of a main DataPipe.
  235. The instance of this class will pass its instance_id to get the next value from its main DataPipe.
  236. Note:
  237. ChildDataPipe, like all other IterDataPipe, follows the single iterator per IterDataPipe constraint.
  238. Since ChildDataPipes share a common buffer, when an iterator is created for one of the ChildDataPipes,
  239. the previous iterators for all ChildDataPipes must be invalidated, with the exception when a ChildDataPipe
  240. hasn't had an iterator created from it since the last invalidation. See the example below.
  241. Example:
  242. >>> # xdoctest: +REQUIRES(module:torchdata)
  243. >>> # Singler Iterator per IteraDataPipe Invalidation
  244. >>> from torchdata.datapipes.iter import IterableWrapper
  245. >>> source_dp = IterableWrapper(range(10))
  246. >>> cdp1, cdp2 = source_dp.fork(num_instances=2)
  247. >>> it1, it2 = iter(cdp1), iter(cdp2)
  248. >>> it3 = iter(cdp1)
  249. >>> # The line above invalidates `it1` and `it2`, and resets `ForkerIterDataPipe`.
  250. >>> it4 = iter(cdp2)
  251. >>> # The line above doesn't invalidate `it3`, because an iterator for `cdp2` hasn't been created since
  252. >>> # the last invalidation.
  253. Args:
  254. main_datapipe: Main DataPipe with a method 'get_next_element_by_instance(instance_id)'
  255. instance_id: integer identifier of this instance
  256. """
  257. _is_child_datapipe: bool = True
  258. def __init__(self, main_datapipe: IterDataPipe, instance_id: int):
  259. assert isinstance(main_datapipe, _ContainerTemplate)
  260. self.main_datapipe: IterDataPipe = main_datapipe
  261. self.instance_id = instance_id
  262. def __iter__(self):
  263. # Note that the logic behind setting iterator ID and `reset` are handled within `hook_iterator`
  264. # We want to separate the code for reset and yield, so that 'reset' executes before __next__ is called
  265. return self.main_datapipe.get_next_element_by_instance(self.instance_id)
  266. def __len__(self):
  267. return self.main_datapipe.get_length_by_instance(self.instance_id)
  268. # This method is called by `hook_iterator` in `_typing.py`.
  269. def _set_main_datapipe_valid_iterator_id(self) -> int:
  270. r"""
  271. Update the valid iterator ID for both this DataPipe object and `main_datapipe`.
  272. `main_datapipe.reset()` is called when the ID is incremented to a new generation.
  273. """
  274. # 1. First time any child iterator is created
  275. if self.main_datapipe._valid_iterator_id is None:
  276. self.main_datapipe._valid_iterator_id = 0 # type: ignore[attr-defined]
  277. # 2. This instance was already in the same generation as `main_datapipe`,
  278. # we need to increment the ID further by 1
  279. elif self.main_datapipe._valid_iterator_id == self._valid_iterator_id: # type: ignore[has-type]
  280. self.main_datapipe._valid_iterator_id += 1 # type: ignore[attr-defined]
  281. # Whenever a new generation of iterator is created, the `main_datapipe` must reset
  282. if not self.main_datapipe.is_every_instance_exhausted():
  283. warnings.warn("Some child DataPipes are not exhausted when __iter__ is called. We are resetting "
  284. "the buffer and each child DataPipe will read from the start again.", UserWarning)
  285. self.main_datapipe.reset()
  286. # 3. Otherwise, the iterator is behind the others, so it will just need to catch up by setting
  287. # the instance's iterator to match that of `main_datapipe`
  288. self._valid_iterator_id = self.main_datapipe._valid_iterator_id
  289. return self._valid_iterator_id
  290. # This method is called by `hook_iterator` in `_typing.py`.
  291. def _check_valid_iterator_id(self, iterator_id) -> bool:
  292. r"""Check the valid iterator ID against that of DataPipe object and that of `main_datapipe`."""
  293. return iterator_id == self._valid_iterator_id and iterator_id == self.main_datapipe._valid_iterator_id
  294. @functional_datapipe('demux')
  295. class DemultiplexerIterDataPipe(IterDataPipe):
  296. r"""
  297. Splits the input DataPipe into multiple child DataPipes, using the given classification function (functional name: ``demux``).
  298. A list of the child DataPipes is returned from this operation.
  299. Args:
  300. datapipe: Iterable DataPipe being filtered
  301. num_instances: number of instances of the DataPipe to create
  302. classifier_fn: a function that maps values to an integer within the range ``[0, num_instances - 1]`` or ``None``
  303. drop_none: defaults to ``False``, if ``True``, the function will skip over elements classified as ``None``
  304. buffer_size: this defines the maximum number of inputs that the buffer can hold across all child
  305. DataPipes while waiting for their values to be yielded.
  306. Defaults to ``1000``. Use ``-1`` for the unlimited buffer.
  307. Examples:
  308. >>> # xdoctest: +REQUIRES(module:torchdata)
  309. >>> from torchdata.datapipes.iter import IterableWrapper
  310. >>> def odd_or_even(n):
  311. ... return n % 2
  312. >>> source_dp = IterableWrapper(range(5))
  313. >>> dp1, dp2 = source_dp.demux(num_instances=2, classifier_fn=odd_or_even)
  314. >>> list(dp1)
  315. [0, 2, 4]
  316. >>> list(dp2)
  317. [1, 3]
  318. >>> # It can also filter out any element that gets `None` from the `classifier_fn`
  319. >>> def odd_or_even_no_zero(n):
  320. ... return n % 2 if n != 0 else None
  321. >>> dp1, dp2 = source_dp.demux(num_instances=2, classifier_fn=odd_or_even_no_zero, drop_none=True)
  322. >>> list(dp1)
  323. [2, 4]
  324. >>> list(dp2)
  325. [1, 3]
  326. """
  327. def __new__(cls, datapipe: IterDataPipe, num_instances: int,
  328. classifier_fn: Callable[[T_co], Optional[int]], drop_none: bool = False, buffer_size: int = 1000):
  329. if num_instances < 1:
  330. raise ValueError(f"Expected `num_instances` larger than 0, but {num_instances} is found")
  331. _check_unpickable_fn(classifier_fn)
  332. # When num_instances == 1, demux can be replaced by filter,
  333. # but keep it as Demultiplexer for the sake of consistency
  334. # like throwing Error when classification result is out of o range
  335. container = _DemultiplexerIterDataPipe(datapipe, num_instances, classifier_fn, drop_none, buffer_size) # type: ignore[abstract]
  336. return [_ChildDataPipe(container, i) for i in range(num_instances)]
  337. class _DemultiplexerIterDataPipe(IterDataPipe, _ContainerTemplate):
  338. r"""
  339. Container to hold instance-specific information on behalf of DemultiplexerIterDataPipe.
  340. It tracks the state of its child DataPipes, maintains the buffer, classifies and yields the next correct value
  341. as requested by the child DataPipes.
  342. """
  343. def __init__(self, datapipe: IterDataPipe[T_co], num_instances: int,
  344. classifier_fn: Callable[[T_co], Optional[int]], drop_none: bool, buffer_size: int):
  345. self.main_datapipe = datapipe
  346. self._datapipe_iterator: Optional[Iterator[Any]] = None
  347. self.num_instances = num_instances
  348. self.buffer_size = buffer_size
  349. if self.buffer_size < 0:
  350. warnings.warn(
  351. "Unlimited buffer size is set for `demux`, "
  352. "please be aware of OOM at random places",
  353. UserWarning
  354. )
  355. self.current_buffer_usage = 0
  356. self.child_buffers: List[Deque[T_co]] = [deque() for _ in range(num_instances)]
  357. self.classifier_fn = classifier_fn
  358. self.drop_none = drop_none
  359. self.main_datapipe_exhausted = False
  360. self._child_stop: List[bool] = [True for _ in range(num_instances)]
  361. def _find_next(self, instance_id: int) -> T_co: # type: ignore[type-var]
  362. while True:
  363. if self.main_datapipe_exhausted or self._child_stop[instance_id]:
  364. raise StopIteration
  365. if self._datapipe_iterator is None:
  366. raise ValueError(
  367. "_datapipe_iterator has not been set, likely because this private method is called directly "
  368. "without invoking get_next_element_by_instance() first.")
  369. value = next(self._datapipe_iterator)
  370. classification = self.classifier_fn(value)
  371. if classification is None and self.drop_none:
  372. StreamWrapper.close_streams(value)
  373. continue
  374. if classification is None or classification >= self.num_instances or classification < 0:
  375. raise ValueError(f"Output of the classification fn should be between 0 and {self.num_instances - 1}. " +
  376. f"{classification} is returned.")
  377. if classification == instance_id:
  378. return value
  379. self.child_buffers[classification].append(value)
  380. self.current_buffer_usage += 1
  381. if self.buffer_size >= 0 and self.current_buffer_usage > self.buffer_size:
  382. raise BufferError(
  383. f"DemultiplexerIterDataPipe buffer overflow, buffer size {self.buffer_size} is insufficient.")
  384. def get_next_element_by_instance(self, instance_id: int):
  385. if self._datapipe_iterator is None and self._child_stop[instance_id]:
  386. self._datapipe_iterator = iter(self.main_datapipe)
  387. self._snapshot_state = _SnapshotState.Iterating # This is necessary for the DataPipe to reset properly.
  388. self.main_datapipe_exhausted = False
  389. for i in range(self.num_instances):
  390. self._child_stop[i] = False
  391. try:
  392. while not self._child_stop[instance_id]:
  393. if self.child_buffers[instance_id]:
  394. self.current_buffer_usage -= 1
  395. yield self.child_buffers[instance_id].popleft()
  396. else:
  397. try:
  398. yield self._find_next(instance_id)
  399. except StopIteration:
  400. self._child_stop[instance_id] = True
  401. self.main_datapipe_exhausted = True
  402. self._datapipe_iterator = None
  403. finally:
  404. self._child_stop[instance_id] = True
  405. # Cleanup _datapipe_iterator for the case that demux exits earlier
  406. if all(self._child_stop):
  407. self._datapipe_iterator = None
  408. if self.child_buffers[instance_id]:
  409. self._cleanup(instance_id)
  410. def is_every_instance_exhausted(self) -> bool:
  411. return self.main_datapipe_exhausted and all(self._child_stop)
  412. def get_length_by_instance(self, instance_id: int) -> int:
  413. raise TypeError
  414. def reset(self) -> None:
  415. self._datapipe_iterator = None
  416. self.current_buffer_usage = 0
  417. self.child_buffers = [deque() for _ in range(self.num_instances)]
  418. self._child_stop = [True for _ in range(self.num_instances)]
  419. self.main_datapipe_exhausted = False
  420. def __getstate__(self):
  421. state = (
  422. self.main_datapipe,
  423. self.num_instances,
  424. self.buffer_size,
  425. self.classifier_fn,
  426. self.drop_none,
  427. self._valid_iterator_id,
  428. self._number_of_samples_yielded,
  429. )
  430. if IterDataPipe.getstate_hook is not None:
  431. return IterDataPipe.getstate_hook(state)
  432. return state
  433. def __setstate__(self, state):
  434. (
  435. self.main_datapipe,
  436. self.num_instances,
  437. self.buffer_size,
  438. self.classifier_fn,
  439. self.drop_none,
  440. self._valid_iterator_id,
  441. self._number_of_samples_yielded,
  442. ) = state
  443. self._datapipe_iterator = None
  444. self.current_buffer_usage = 0
  445. self.child_buffers = [deque() for _ in range(self.num_instances)]
  446. self._child_stop = [True for _ in range(self.num_instances)]
  447. self.main_datapipe_exhausted = False
  448. def _cleanup(self, instance_id: Optional[int] = None):
  449. ids = range(self.num_instances) if instance_id is None else [instance_id, ]
  450. for i in ids:
  451. q = self.child_buffers[i]
  452. while q:
  453. d = q.popleft()
  454. StreamWrapper.close_streams(d)
  455. def __del__(self):
  456. self._cleanup()
  457. @functional_datapipe('mux')
  458. class MultiplexerIterDataPipe(IterDataPipe):
  459. r"""
  460. Yields one element at a time from each of the input Iterable DataPipes (functional name: ``mux``).
  461. As in, one element from the 1st input DataPipe, then one element from the 2nd DataPipe in the next iteration,
  462. and so on. It ends when the shortest input DataPipe is exhausted.
  463. Args:
  464. datapipes: Iterable DataPipes that will take turn to yield their elements, until the shortest DataPipe is exhausted
  465. Example:
  466. >>> # xdoctest: +REQUIRES(module:torchdata)
  467. >>> from torchdata.datapipes.iter import IterableWrapper
  468. >>> dp1, dp2, dp3 = IterableWrapper(range(3)), IterableWrapper(range(10, 15)), IterableWrapper(range(20, 25))
  469. >>> list(dp1.mux(dp2, dp3))
  470. [0, 10, 20, 1, 11, 21, 2, 12, 22]
  471. """
  472. def __init__(self, *datapipes):
  473. self.datapipes = datapipes
  474. self.buffer: List = [] # Store values to be yielded only when every iterator provides one
  475. def __iter__(self):
  476. iterators = [iter(x) for x in self.datapipes]
  477. while len(iterators):
  478. for it in iterators:
  479. try:
  480. value = next(it)
  481. self.buffer.append(value)
  482. except StopIteration:
  483. self.buffer.clear()
  484. return
  485. yield from self.buffer
  486. self.buffer.clear()
  487. def __len__(self):
  488. if all(isinstance(dp, Sized) for dp in self.datapipes):
  489. return min(len(dp) for dp in self.datapipes) * len(self.datapipes)
  490. else:
  491. raise TypeError(f"{type(self).__name__} instance doesn't have valid length")
  492. def reset(self) -> None:
  493. self.buffer = []
  494. def __getstate__(self):
  495. state = (
  496. self.datapipes,
  497. self._valid_iterator_id,
  498. self._number_of_samples_yielded,
  499. )
  500. if IterDataPipe.getstate_hook is not None:
  501. return IterDataPipe.getstate_hook(state)
  502. return state
  503. def __setstate__(self, state):
  504. (
  505. self.datapipes,
  506. self._valid_iterator_id,
  507. self._number_of_samples_yielded,
  508. ) = state
  509. self.buffer = []
  510. def __del__(self):
  511. self.buffer.clear()
  512. @functional_datapipe('zip')
  513. class ZipperIterDataPipe(IterDataPipe[Tuple[T_co]]):
  514. r"""
  515. Aggregates elements into a tuple from each of the input DataPipes (functional name: ``zip``).
  516. The output is stopped as soon as the shortest input DataPipe is exhausted.
  517. Args:
  518. *datapipes: Iterable DataPipes being aggregated
  519. Example:
  520. >>> # xdoctest: +REQUIRES(module:torchdata)
  521. >>> from torchdata.datapipes.iter import IterableWrapper
  522. >>> dp1, dp2, dp3 = IterableWrapper(range(5)), IterableWrapper(range(10, 15)), IterableWrapper(range(20, 25))
  523. >>> list(dp1.zip(dp2, dp3))
  524. [(0, 10, 20), (1, 11, 21), (2, 12, 22), (3, 13, 23), (4, 14, 24)]
  525. """
  526. datapipes: Tuple[IterDataPipe]
  527. def __init__(self, *datapipes: IterDataPipe):
  528. if not all(isinstance(dp, IterDataPipe) for dp in datapipes):
  529. raise TypeError("All inputs are required to be `IterDataPipe` "
  530. "for `ZipIterDataPipe`.")
  531. super().__init__()
  532. self.datapipes = datapipes # type: ignore[assignment]
  533. def __iter__(self) -> Iterator[Tuple[T_co]]:
  534. iterators = [iter(datapipe) for datapipe in self.datapipes]
  535. yield from zip(*iterators)
  536. def __len__(self) -> int:
  537. if all(isinstance(dp, Sized) for dp in self.datapipes):
  538. return min(len(dp) for dp in self.datapipes)
  539. else:
  540. raise TypeError(f"{type(self).__name__} instance doesn't have valid length")