combining.py 25 KB

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