datapipe.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. import functools
  2. import pickle
  3. from typing import Dict, Callable, Optional, TypeVar, Generic, Iterator
  4. from torch.utils.data.datapipes._typing import _DataPipeMeta, _IterDataPipeMeta
  5. from torch.utils.data.datapipes._hook_iterator import _SnapshotState
  6. from torch.utils.data.datapipes.utils.common import (
  7. _deprecation_warning,
  8. _iter_deprecated_functional_names,
  9. _map_deprecated_functional_names,
  10. )
  11. from torch.utils.data.dataset import Dataset, IterableDataset
  12. from torch.utils._import_utils import import_dill
  13. dill = import_dill()
  14. HAS_DILL = dill is not None
  15. __all__ = [
  16. "DataChunk",
  17. "DFIterDataPipe",
  18. "IterDataPipe",
  19. "MapDataPipe",
  20. ]
  21. T = TypeVar('T')
  22. T_co = TypeVar('T_co', covariant=True)
  23. UNTRACABLE_DATAFRAME_PIPES = ['batch', # As it returns DataChunks
  24. 'groupby', # As it returns DataChunks
  25. '_dataframes_as_tuples', # As it unpacks DF
  26. 'trace_as_dataframe', # As it used to mark DF for tracing
  27. ]
  28. class IterDataPipe(IterableDataset[T_co], metaclass=_IterDataPipeMeta):
  29. r"""
  30. Iterable-style DataPipe.
  31. All DataPipes that represent an iterable of data samples should subclass this.
  32. This style of DataPipes is particularly useful when data come from a stream, or
  33. when the number of samples is too large to fit them all in memory. ``IterDataPipe`` is lazily initialized and its
  34. elements are computed only when ``next()`` is called on the iterator of an ``IterDataPipe``.
  35. All subclasses should overwrite :meth:`__iter__`, which would return an
  36. iterator of samples in this DataPipe. Calling ``__iter__`` of an ``IterDataPipe`` automatically invokes its
  37. method ``reset()``, which by default performs no operation. When writing a custom ``IterDataPipe``, users should
  38. override ``reset()`` if necessary. The common usages include resetting buffers, pointers,
  39. and various state variables within the custom ``IterDataPipe``.
  40. Note:
  41. Only `one` iterator can be valid for each ``IterDataPipe`` at a time,
  42. and the creation a second iterator will invalidate the first one. This constraint is necessary because
  43. some ``IterDataPipe`` have internal buffers, whose states can become invalid if there are multiple iterators.
  44. The code example below presents details on how this constraint looks in practice.
  45. If you have any feedback related to this constraint, please see `GitHub IterDataPipe Single Iterator Issue`_.
  46. These DataPipes can be invoked in two ways, using the class constructor or applying their
  47. functional form onto an existing ``IterDataPipe`` (recommended, available to most but not all DataPipes).
  48. You can chain multiple `IterDataPipe` together to form a pipeline that will perform multiple
  49. operations in succession.
  50. .. _GitHub IterDataPipe Single Iterator Issue:
  51. https://github.com/pytorch/data/issues/45
  52. Note:
  53. When a subclass is used with :class:`~torch.utils.data.DataLoader`, each
  54. item in the DataPipe will be yielded from the :class:`~torch.utils.data.DataLoader`
  55. iterator. When :attr:`num_workers > 0`, each worker process will have a
  56. different copy of the DataPipe object, so it is often desired to configure
  57. each copy independently to avoid having duplicate data returned from the
  58. workers. :func:`~torch.utils.data.get_worker_info`, when called in a worker
  59. process, returns information about the worker. It can be used in either the
  60. dataset's :meth:`__iter__` method or the :class:`~torch.utils.data.DataLoader` 's
  61. :attr:`worker_init_fn` option to modify each copy's behavior.
  62. Examples:
  63. General Usage:
  64. >>> # xdoctest: +SKIP
  65. >>> from torchdata.datapipes.iter import IterableWrapper, Mapper
  66. >>> dp = IterableWrapper(range(10))
  67. >>> map_dp_1 = Mapper(dp, lambda x: x + 1) # Using class constructor
  68. >>> map_dp_2 = dp.map(lambda x: x + 1) # Using functional form (recommended)
  69. >>> list(map_dp_1)
  70. [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  71. >>> list(map_dp_2)
  72. [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  73. >>> filter_dp = map_dp_1.filter(lambda x: x % 2 == 0)
  74. >>> list(filter_dp)
  75. [2, 4, 6, 8, 10]
  76. Single Iterator Constraint Example:
  77. >>> from torchdata.datapipes.iter import IterableWrapper, Mapper
  78. >>> source_dp = IterableWrapper(range(10))
  79. >>> it1 = iter(source_dp)
  80. >>> list(it1)
  81. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  82. >>> it1 = iter(source_dp)
  83. >>> it2 = iter(source_dp) # The creation of a new iterator invalidates `it1`
  84. >>> next(it2)
  85. 0
  86. >>> next(it1) # Further usage of `it1` will raise a `RunTimeError`
  87. """
  88. functions: Dict[str, Callable] = {}
  89. reduce_ex_hook: Optional[Callable] = None
  90. getstate_hook: Optional[Callable] = None
  91. str_hook: Optional[Callable] = None
  92. repr_hook: Optional[Callable] = None
  93. _valid_iterator_id: Optional[int] = None
  94. _number_of_samples_yielded: int = 0
  95. _snapshot_state: _SnapshotState = _SnapshotState.NotStarted
  96. _fast_forward_iterator: Optional[Iterator] = None
  97. def __iter__(self) -> Iterator[T_co]:
  98. return self
  99. def __getattr__(self, attribute_name):
  100. if attribute_name in IterDataPipe.functions:
  101. if attribute_name in _iter_deprecated_functional_names:
  102. kwargs = _iter_deprecated_functional_names[attribute_name]
  103. _deprecation_warning(**kwargs)
  104. f = IterDataPipe.functions[attribute_name]
  105. function = functools.partial(f, self)
  106. functools.update_wrapper(wrapper=function, wrapped=f, assigned=("__doc__",))
  107. return function
  108. else:
  109. raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{attribute_name}")
  110. @classmethod
  111. def register_function(cls, function_name, function):
  112. cls.functions[function_name] = function
  113. @classmethod
  114. def register_datapipe_as_function(cls, function_name, cls_to_register, enable_df_api_tracing=False):
  115. if function_name in cls.functions:
  116. raise Exception(f"Unable to add DataPipe function name {function_name} as it is already taken") # noqa: TRY002
  117. def class_function(cls, enable_df_api_tracing, source_dp, *args, **kwargs):
  118. result_pipe = cls(source_dp, *args, **kwargs)
  119. if isinstance(result_pipe, IterDataPipe):
  120. if enable_df_api_tracing or isinstance(source_dp, DFIterDataPipe):
  121. if function_name not in UNTRACABLE_DATAFRAME_PIPES:
  122. result_pipe = result_pipe.trace_as_dataframe()
  123. return result_pipe
  124. function = functools.partial(
  125. class_function, cls_to_register, enable_df_api_tracing
  126. )
  127. functools.update_wrapper(
  128. wrapper=function, wrapped=cls_to_register, assigned=("__doc__",)
  129. )
  130. cls.functions[function_name] = function
  131. def __getstate__(self):
  132. """
  133. Serialize `lambda` functions when `dill` is available.
  134. If this doesn't cover your custom DataPipe's use case, consider writing custom methods for
  135. `__getstate__` and `__setstate__`, or use `pickle.dumps` for serialization.
  136. """
  137. state = self.__dict__
  138. if IterDataPipe.getstate_hook is not None:
  139. return IterDataPipe.getstate_hook(state)
  140. return state
  141. def __reduce_ex__(self, *args, **kwargs):
  142. if IterDataPipe.reduce_ex_hook is not None:
  143. try:
  144. return IterDataPipe.reduce_ex_hook(self)
  145. except NotImplementedError:
  146. pass
  147. return super().__reduce_ex__(*args, **kwargs)
  148. @classmethod
  149. def set_getstate_hook(cls, hook_fn):
  150. if IterDataPipe.getstate_hook is not None and hook_fn is not None:
  151. raise Exception("Attempt to override existing getstate_hook") # noqa: TRY002
  152. IterDataPipe.getstate_hook = hook_fn
  153. @classmethod
  154. def set_reduce_ex_hook(cls, hook_fn):
  155. if IterDataPipe.reduce_ex_hook is not None and hook_fn is not None:
  156. raise Exception("Attempt to override existing reduce_ex_hook") # noqa: TRY002
  157. IterDataPipe.reduce_ex_hook = hook_fn
  158. def __repr__(self):
  159. if self.repr_hook is not None:
  160. return self.repr_hook(self)
  161. # Instead of showing <torch. ... .MapperIterDataPipe object at 0x.....>, return the class name
  162. return str(self.__class__.__qualname__)
  163. def __str__(self):
  164. if self.str_hook is not None:
  165. return self.str_hook(self)
  166. # Instead of showing <torch. ... .MapperIterDataPipe object at 0x.....>, return the class name
  167. return str(self.__class__.__qualname__)
  168. def __dir__(self):
  169. # for auto-completion in a REPL (e.g. Jupyter notebook)
  170. return list(super().__dir__()) + list(self.functions.keys())
  171. def reset(self) -> None:
  172. r"""
  173. Reset the `IterDataPipe` to the initial state.
  174. By default, no-op. For subclasses of `IterDataPipe`, depending on their functionalities,
  175. they may want to override this method with implementations that
  176. may clear the buffers and reset pointers of the DataPipe.
  177. The `reset` method is always called when `__iter__` is called as part of `hook_iterator`.
  178. """
  179. pass
  180. class DFIterDataPipe(IterDataPipe):
  181. def _is_dfpipe(self):
  182. return True
  183. class MapDataPipe(Dataset[T_co], metaclass=_DataPipeMeta):
  184. r"""
  185. Map-style DataPipe.
  186. All datasets that represent a map from keys to data samples should subclass this.
  187. Subclasses should overwrite :meth:`__getitem__`, supporting fetching a
  188. data sample for a given, unique key. Subclasses can also optionally overwrite
  189. :meth:`__len__`, which is expected to return the size of the dataset by many
  190. :class:`~torch.utils.data.Sampler` implementations and the default options
  191. of :class:`~torch.utils.data.DataLoader`.
  192. These DataPipes can be invoked in two ways, using the class constructor or applying their
  193. functional form onto an existing `MapDataPipe` (recommend, available to most but not all DataPipes).
  194. Note:
  195. :class:`~torch.utils.data.DataLoader` by default constructs an index
  196. sampler that yields integral indices. To make it work with a map-style
  197. DataPipe with non-integral indices/keys, a custom sampler must be provided.
  198. Example:
  199. >>> # xdoctest: +SKIP
  200. >>> from torchdata.datapipes.map import SequenceWrapper, Mapper
  201. >>> dp = SequenceWrapper(range(10))
  202. >>> map_dp_1 = dp.map(lambda x: x + 1) # Using functional form (recommended)
  203. >>> list(map_dp_1)
  204. [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  205. >>> map_dp_2 = Mapper(dp, lambda x: x + 1) # Using class constructor
  206. >>> list(map_dp_2)
  207. [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  208. >>> batch_dp = map_dp_1.batch(batch_size=2)
  209. >>> list(batch_dp)
  210. [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
  211. """
  212. functions: Dict[str, Callable] = {}
  213. reduce_ex_hook: Optional[Callable] = None
  214. getstate_hook: Optional[Callable] = None
  215. str_hook: Optional[Callable] = None
  216. repr_hook: Optional[Callable] = None
  217. def __getattr__(self, attribute_name):
  218. if attribute_name in MapDataPipe.functions:
  219. if attribute_name in _map_deprecated_functional_names:
  220. kwargs = _map_deprecated_functional_names[attribute_name]
  221. _deprecation_warning(**kwargs)
  222. f = MapDataPipe.functions[attribute_name]
  223. function = functools.partial(f, self)
  224. functools.update_wrapper(wrapper=function, wrapped=f, assigned=("__doc__",))
  225. return function
  226. else:
  227. raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{attribute_name}")
  228. @classmethod
  229. def register_function(cls, function_name, function):
  230. cls.functions[function_name] = function
  231. @classmethod
  232. def register_datapipe_as_function(cls, function_name, cls_to_register):
  233. if function_name in cls.functions:
  234. raise Exception(f"Unable to add DataPipe function name {function_name} as it is already taken") # noqa: TRY002
  235. def class_function(cls, source_dp, *args, **kwargs):
  236. result_pipe = cls(source_dp, *args, **kwargs)
  237. return result_pipe
  238. function = functools.partial(class_function, cls_to_register)
  239. functools.update_wrapper(
  240. wrapper=function, wrapped=cls_to_register, assigned=("__doc__",)
  241. )
  242. cls.functions[function_name] = function
  243. def __getstate__(self):
  244. """
  245. Serialize `lambda` functions when `dill` is available.
  246. If this doesn't cover your custom DataPipe's use case, consider writing custom methods for
  247. `__getstate__` and `__setstate__`, or use `pickle.dumps` for serialization.
  248. """
  249. state = self.__dict__
  250. if MapDataPipe.getstate_hook is not None:
  251. return MapDataPipe.getstate_hook(state)
  252. return state
  253. def __reduce_ex__(self, *args, **kwargs):
  254. if MapDataPipe.reduce_ex_hook is not None:
  255. try:
  256. return MapDataPipe.reduce_ex_hook(self)
  257. except NotImplementedError:
  258. pass
  259. return super().__reduce_ex__(*args, **kwargs)
  260. @classmethod
  261. def set_getstate_hook(cls, hook_fn):
  262. if MapDataPipe.getstate_hook is not None and hook_fn is not None:
  263. raise Exception("Attempt to override existing getstate_hook") # noqa: TRY002
  264. MapDataPipe.getstate_hook = hook_fn
  265. @classmethod
  266. def set_reduce_ex_hook(cls, hook_fn):
  267. if MapDataPipe.reduce_ex_hook is not None and hook_fn is not None:
  268. raise Exception("Attempt to override existing reduce_ex_hook") # noqa: TRY002
  269. MapDataPipe.reduce_ex_hook = hook_fn
  270. def __repr__(self):
  271. if self.repr_hook is not None:
  272. return self.repr_hook(self)
  273. # Instead of showing <torch. ... .MapperMapDataPipe object at 0x.....>, return the class name
  274. return str(self.__class__.__qualname__)
  275. def __str__(self):
  276. if self.str_hook is not None:
  277. return self.str_hook(self)
  278. # Instead of showing <torch. ... .MapperMapDataPipe object at 0x.....>, return the class name
  279. return str(self.__class__.__qualname__)
  280. def __dir__(self):
  281. # for auto-completion in a REPL (e.g. Jupyter notebook)
  282. return list(super().__dir__()) + list(self.functions.keys())
  283. class _DataPipeSerializationWrapper:
  284. def __init__(self, datapipe):
  285. self._datapipe = datapipe
  286. def __getstate__(self):
  287. use_dill = False
  288. try:
  289. value = pickle.dumps(self._datapipe)
  290. except Exception:
  291. if HAS_DILL:
  292. value = dill.dumps(self._datapipe)
  293. use_dill = True
  294. else:
  295. raise
  296. return (value, use_dill)
  297. def __setstate__(self, state):
  298. value, use_dill = state
  299. if use_dill:
  300. self._datapipe = dill.loads(value)
  301. else:
  302. self._datapipe = pickle.loads(value)
  303. def __len__(self):
  304. try:
  305. return len(self._datapipe)
  306. except Exception as e:
  307. raise TypeError(
  308. f"{type(self).__name__} instance doesn't have valid length"
  309. ) from e
  310. class _IterDataPipeSerializationWrapper(_DataPipeSerializationWrapper, IterDataPipe):
  311. def __init__(self, datapipe: IterDataPipe[T_co]):
  312. super().__init__(datapipe)
  313. self._datapipe_iter: Optional[Iterator[T_co]] = None
  314. def __iter__(self) -> "_IterDataPipeSerializationWrapper":
  315. self._datapipe_iter = iter(self._datapipe)
  316. return self
  317. def __next__(self) -> T_co: # type: ignore[type-var]
  318. assert self._datapipe_iter is not None
  319. return next(self._datapipe_iter)
  320. class _MapDataPipeSerializationWrapper(_DataPipeSerializationWrapper, MapDataPipe):
  321. def __getitem__(self, idx):
  322. return self._datapipe[idx]
  323. class DataChunk(list, Generic[T]):
  324. def __init__(self, items):
  325. super().__init__(items)
  326. self.items = items
  327. def as_str(self, indent=''):
  328. res = indent + "[" + ", ".join(str(i) for i in iter(self)) + "]"
  329. return res
  330. def __iter__(self) -> Iterator[T]:
  331. yield from super().__iter__()
  332. def raw_iterator(self) -> T: # type: ignore[misc]
  333. yield from self.items