callable.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. import functools
  2. from collections import namedtuple
  3. from typing import Callable, Iterator, Sized, TypeVar, Optional, Union, Any, Dict, List
  4. from torch.utils.data.datapipes._decorator import functional_datapipe
  5. from torch.utils.data._utils.collate import default_collate
  6. from torch.utils.data.datapipes.dataframe import dataframe_wrapper as df_wrapper
  7. from torch.utils.data.datapipes.datapipe import IterDataPipe
  8. from torch.utils.data.datapipes.utils.common import (_check_unpickable_fn,
  9. validate_input_col)
  10. __all__ = [
  11. "CollatorIterDataPipe",
  12. "MapperIterDataPipe",
  13. ]
  14. T_co = TypeVar("T_co", covariant=True)
  15. @functional_datapipe("map")
  16. class MapperIterDataPipe(IterDataPipe[T_co]):
  17. r"""
  18. Applies a function over each item from the source DataPipe (functional name: ``map``).
  19. The function can be any regular Python function or partial object. Lambda
  20. function is not recommended as it is not supported by pickle.
  21. Args:
  22. datapipe: Source Iterable DataPipe
  23. fn: Function being applied over each item
  24. input_col: Index or indices of data which ``fn`` is applied, such as:
  25. - ``None`` as default to apply ``fn`` to the data directly.
  26. - Integer(s) is used for list/tuple.
  27. - Key(s) is used for dict.
  28. output_col: Index of data where result of ``fn`` is placed. ``output_col`` can be specified
  29. only when ``input_col`` is not ``None``
  30. - ``None`` as default to replace the index that ``input_col`` specified; For ``input_col`` with
  31. multiple indices, the left-most one is used, and other indices will be removed.
  32. - Integer is used for list/tuple. ``-1`` represents to append result at the end.
  33. - Key is used for dict. New key is acceptable.
  34. Example:
  35. >>> # xdoctest: +SKIP
  36. >>> from torchdata.datapipes.iter import IterableWrapper, Mapper
  37. >>> def add_one(x):
  38. ... return x + 1
  39. >>> dp = IterableWrapper(range(10))
  40. >>> map_dp_1 = dp.map(add_one) # Invocation via functional form is preferred
  41. >>> list(map_dp_1)
  42. [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  43. >>> # We discourage the usage of `lambda` functions as they are not serializable with `pickle`
  44. >>> # Use `functools.partial` or explicitly define the function instead
  45. >>> map_dp_2 = Mapper(dp, lambda x: x + 1)
  46. >>> list(map_dp_2)
  47. [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  48. """
  49. datapipe: IterDataPipe
  50. fn: Callable
  51. def __init__(
  52. self,
  53. datapipe: IterDataPipe,
  54. fn: Callable,
  55. input_col=None,
  56. output_col=None,
  57. ) -> None:
  58. super().__init__()
  59. self.datapipe = datapipe
  60. _check_unpickable_fn(fn)
  61. self.fn = fn # type: ignore[assignment]
  62. self.input_col = input_col
  63. if input_col is None and output_col is not None:
  64. raise ValueError("`output_col` must be None when `input_col` is None.")
  65. if isinstance(output_col, (list, tuple)):
  66. if len(output_col) > 1:
  67. raise ValueError("`output_col` must be a single-element list or tuple")
  68. output_col = output_col[0]
  69. self.output_col = output_col
  70. validate_input_col(fn, input_col)
  71. def _apply_fn(self, data):
  72. if self.input_col is None and self.output_col is None:
  73. return self.fn(data)
  74. if self.input_col is None:
  75. res = self.fn(data)
  76. elif isinstance(self.input_col, (list, tuple)):
  77. args = tuple(data[col] for col in self.input_col)
  78. res = self.fn(*args)
  79. else:
  80. res = self.fn(data[self.input_col])
  81. # Copy tuple to list and run in-place modification because tuple is immutable.
  82. if isinstance(data, tuple):
  83. t_flag = True
  84. data = list(data)
  85. else:
  86. t_flag = False
  87. if self.output_col is None:
  88. if isinstance(self.input_col, (list, tuple)):
  89. data[self.input_col[0]] = res
  90. for idx in sorted(self.input_col[1:], reverse=True):
  91. del data[idx]
  92. else:
  93. data[self.input_col] = res
  94. else:
  95. if self.output_col == -1:
  96. data.append(res)
  97. else:
  98. data[self.output_col] = res
  99. # Convert list back to tuple
  100. return tuple(data) if t_flag else data
  101. def __iter__(self) -> Iterator[T_co]:
  102. for data in self.datapipe:
  103. yield self._apply_fn(data)
  104. def __len__(self) -> int:
  105. if isinstance(self.datapipe, Sized):
  106. return len(self.datapipe)
  107. raise TypeError(
  108. "{} instance doesn't have valid length".format(type(self).__name__)
  109. )
  110. def _collate_helper(conversion, item):
  111. # TODO(VitalyFedyunin): Verify that item is any sort of batch
  112. if len(item.items) > 1:
  113. # TODO(VitalyFedyunin): Compact all batch dataframes into one
  114. raise Exception("Only supports one DataFrame per batch")
  115. df = item[0]
  116. columns_name = df_wrapper.get_columns(df)
  117. tuple_names: List = []
  118. tuple_values: List = []
  119. for name in conversion.keys():
  120. if name not in columns_name:
  121. raise Exception("Conversion keys missmatch")
  122. for name in columns_name:
  123. if name in conversion:
  124. if not callable(conversion[name]):
  125. raise Exception('Collate (DF)DataPipe requires callable as dict values')
  126. collation_fn = conversion[name]
  127. else:
  128. # TODO(VitalyFedyunin): Add default collation into df_wrapper
  129. try:
  130. import torcharrow.pytorch as tap # type: ignore[import]
  131. collation_fn = tap.rec.Default()
  132. except Exception as e:
  133. raise Exception("unable to import default collation function from the TorchArrow") from e
  134. tuple_names.append(str(name))
  135. value = collation_fn(df[name])
  136. tuple_values.append(value)
  137. # TODO(VitalyFedyunin): We can dynamically extract types from the tuple_values here
  138. # TODO(VitalyFedyunin): Instead of ignoring mypy error, make sure tuple_names is not empty
  139. tpl_cls = namedtuple("CollateResult", tuple_names) # type: ignore[misc]
  140. tuple = tpl_cls(*tuple_values)
  141. return tuple
  142. @functional_datapipe("collate")
  143. class CollatorIterDataPipe(MapperIterDataPipe):
  144. r"""
  145. Collates samples from DataPipe to Tensor(s) by a custom collate function (functional name: ``collate``).
  146. By default, it uses :func:`torch.utils.data.default_collate`.
  147. .. note::
  148. While writing a custom collate function, you can import :func:`torch.utils.data.default_collate` for the
  149. default behavior and `functools.partial` to specify any additional arguments.
  150. Args:
  151. datapipe: Iterable DataPipe being collated
  152. collate_fn: Customized collate function to collect and combine data or a batch of data.
  153. Default function collates to Tensor(s) based on data type.
  154. Example:
  155. >>> # xdoctest: +SKIP
  156. >>> # Convert integer data to float Tensor
  157. >>> class MyIterDataPipe(torch.utils.data.IterDataPipe):
  158. ... def __init__(self, start, end):
  159. ... super(MyIterDataPipe).__init__()
  160. ... assert end > start, "this example code only works with end >= start"
  161. ... self.start = start
  162. ... self.end = end
  163. ...
  164. ... def __iter__(self):
  165. ... return iter(range(self.start, self.end))
  166. ...
  167. ... def __len__(self):
  168. ... return self.end - self.start
  169. ...
  170. >>> ds = MyIterDataPipe(start=3, end=7)
  171. >>> print(list(ds))
  172. [3, 4, 5, 6]
  173. >>> def collate_fn(batch):
  174. ... return torch.tensor(batch, dtype=torch.float)
  175. ...
  176. >>> collated_ds = CollateIterDataPipe(ds, collate_fn=collate_fn)
  177. >>> print(list(collated_ds))
  178. [tensor(3.), tensor(4.), tensor(5.), tensor(6.)]
  179. """
  180. def __init__(
  181. self,
  182. datapipe: IterDataPipe,
  183. conversion: Optional[
  184. Union[
  185. Callable[..., Any],
  186. Dict[Union[str, Any], Union[Callable, Any]],
  187. ]
  188. ] = default_collate,
  189. collate_fn: Optional[Callable] = None,
  190. ) -> None:
  191. # TODO(VitalyFedyunin): Replace `Callable[..., Any]` with `Callable[[IColumn], Any]`
  192. # TODO(VitalyFedyunin): Replace with `Dict[Union[str, IColumn], Union[Callable, Enum]]`
  193. if collate_fn is not None:
  194. super().__init__(datapipe, fn=collate_fn)
  195. else:
  196. if callable(conversion):
  197. super().__init__(datapipe, fn=conversion)
  198. else:
  199. # TODO(VitalyFedyunin): Validate passed dictionary
  200. collate_fn = functools.partial(_collate_helper, conversion)
  201. super().__init__(datapipe, fn=collate_fn)