datapipe.py 16 KB

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