rearrange.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. from __future__ import annotations
  2. import functools
  3. from typing import TYPE_CHECKING, Union
  4. import torch
  5. from functorch.dim import dims # noqa: F401
  6. from ._parsing import (
  7. _ellipsis,
  8. AnonymousAxis,
  9. comma_separate,
  10. parse_pattern,
  11. validate_rearrange_expressions,
  12. )
  13. if TYPE_CHECKING:
  14. from collections.abc import Callable, Sequence
  15. __all__ = ["rearrange"]
  16. @functools.lru_cache(256)
  17. def _create_rearrange_callable(
  18. tensor_ndim: int, pattern: str, **axes_lengths: int
  19. ) -> Callable[[torch.Tensor], torch.Tensor]:
  20. r"""Translate an `einops`-style pattern into a callable that performs the rearrange using first-class dimensions.
  21. Since the an equivalent result is computed for tensors with the same number of dimensions, with the same pattern and
  22. specified axes lengths, this function can be memoized.
  23. Args:
  24. tensor_ndim (int): the number of dimensions in the tensor to rearrange
  25. pattern (str): the `einops`-style rearrangement pattern
  26. axes_lengths (int): any additional length specifications for dimensions
  27. Returns:
  28. Callable[[torch.Tensor], torch.Tensor]: a callable that performs the rearrangement
  29. """
  30. left, right = parse_pattern(pattern, axes_lengths)
  31. validate_rearrange_expressions(left, right, axes_lengths)
  32. n_anon_dims = sum(not dim for dim in left.composition)
  33. if left.has_ellipsis:
  34. n_ellipsis_dims = tensor_ndim - (len(left.composition) - 1)
  35. n_named_dims = len(left.identifiers) - 1
  36. if (pattern_ndim := n_anon_dims + n_named_dims) > tensor_ndim:
  37. raise ValueError(
  38. f"Number of dimensions in pattern ({pattern_ndim}) must be less than or equal to the number of "
  39. f"dimensions in the tensor ({tensor_ndim})"
  40. )
  41. else:
  42. n_ellipsis_dims = 0
  43. n_named_dims = len(left.identifiers)
  44. if (pattern_ndim := len(left.composition)) != tensor_ndim:
  45. raise ValueError(
  46. f"Number of dimensions in pattern ({pattern_ndim}) must be equal to the number of dimensions in "
  47. f"the tensor ({tensor_ndim})"
  48. )
  49. n_dims = n_named_dims + n_ellipsis_dims + n_anon_dims
  50. if n_dims == 0:
  51. # an identity rearrangement on a 0-dimension tensor
  52. return lambda tensor: tensor
  53. first_class_dims: tuple[str, ...] = tuple(f"d{i}" for i in range(n_dims))
  54. identifier_dim_map: dict[Union[str, AnonymousAxis], tuple[str, ...]] = {}
  55. anon_axes: list[AnonymousAxis] = []
  56. # map the left-hand side identifiers to strings representing first class dims
  57. dims_i = 0
  58. for dimension in left.composition:
  59. if isinstance(dimension, list):
  60. for identifier in dimension:
  61. # non-unitary anon axes are not allowed in rearrange & unitary anon axes are represented as empty lists
  62. if not isinstance(identifier, str):
  63. raise AssertionError(f"Expected str, got {type(identifier)}")
  64. identifier_dim_map[identifier] = (first_class_dims[dims_i],)
  65. dims_i += 1
  66. if not dimension:
  67. # unitary anonymous axis
  68. anon_axis = AnonymousAxis("1")
  69. identifier_dim_map[anon_axis] = (first_class_dims[dims_i],)
  70. anon_axes.append(anon_axis)
  71. dimension.append(anon_axis)
  72. dims_i += 1
  73. elif dimension == _ellipsis:
  74. identifier = _ellipsis
  75. identifier_dim_map[identifier] = tuple(
  76. first_class_dims[dims_i + j] for j in range(n_ellipsis_dims)
  77. )
  78. dims_i += n_ellipsis_dims
  79. else:
  80. raise ValueError(f"Unexpected dimension: {dimension}")
  81. def composition_to_dims(
  82. composition: Sequence[Union[list[Union[str, AnonymousAxis]], str]],
  83. ) -> list[Union[str, tuple[str, ...]]]:
  84. """Convert a `ParsedExpression.composition` into a `Tensor.__getitem__` index of strings representing first
  85. class dims."""
  86. dim_composition: list[Union[str, tuple[str, ...]]] = []
  87. for dimension in composition:
  88. if isinstance(dimension, list):
  89. dim_composition.append(
  90. tuple(
  91. dim
  92. for identifier in dimension
  93. for dim in identifier_dim_map[identifier]
  94. )
  95. )
  96. elif dimension == _ellipsis:
  97. dim_composition.extend(identifier_dim_map[_ellipsis])
  98. else:
  99. raise ValueError(f"Unexpected dimension: {dimension}")
  100. return dim_composition
  101. left_dims = composition_to_dims(left.composition)
  102. right_dims = composition_to_dims(right.composition)
  103. anon_dims = tuple(identifier_dim_map[axis][0] for axis in anon_axes)
  104. specified_lengths = tuple(
  105. (identifier_dim_map[axis][0], length) for axis, length in axes_lengths.items()
  106. )
  107. custom_rearrange_callable_name = "do_rearrange"
  108. custom_rearrange_callable_code = (
  109. (
  110. f"def {custom_rearrange_callable_name}(tensor):\n"
  111. f" {comma_separate(first_class_dims)} = dims({n_dims})\n"
  112. )
  113. + (
  114. "".join(
  115. f" {dim}.size = {length}\n" for (dim, length) in specified_lengths
  116. )
  117. if specified_lengths
  118. else ""
  119. )
  120. + f" tensor = tensor[{comma_separate(left_dims)}].order({comma_separate(right_dims)})\n"
  121. + (
  122. f" return tensor.sum({comma_separate([anon_dims])}, keepdim=False)\n"
  123. if anon_dims
  124. else " return tensor\n"
  125. )
  126. )
  127. exec(custom_rearrange_callable_code)
  128. return locals()[custom_rearrange_callable_name]
  129. def rearrange(
  130. tensor: Union[torch.Tensor, list[torch.Tensor], tuple[torch.Tensor, ...]],
  131. pattern: str,
  132. **axes_lengths: int,
  133. ) -> torch.Tensor:
  134. r"""A native implementation of `einops.rearrange`, a reader-friendly smart element reordering for multidimensional
  135. tensors. This operation includes functionality of transpose (axes permutation), reshape (view), squeeze, unsqueeze,
  136. stack, concatenate and other operations.
  137. See: https://einops.rocks/api/rearrange/
  138. Args:
  139. tensor (Tensor or sequence of Tensor): the tensor(s) to rearrange
  140. pattern (str): the rearrangement pattern
  141. axes_lengths (int): any additional length specifications for dimensions
  142. Returns:
  143. Tensor: the rearranged tensor
  144. Examples:
  145. >>> # suppose we have a set of 32 images in "h w c" format (height-width-channel)
  146. >>> images = torch.randn((32, 30, 40, 3))
  147. >>> # stack along first (batch) axis, output is a single array
  148. >>> rearrange(images, "b h w c -> b h w c").shape
  149. torch.Size([32, 30, 40, 3])
  150. >>> # concatenate images along height (vertical axis), 960 = 32 * 30
  151. >>> rearrange(images, "b h w c -> (b h) w c").shape
  152. torch.Size([960, 40, 3])
  153. >>> # concatenated images along horizontal axis, 1280 = 32 * 40
  154. >>> rearrange(images, "b h w c -> h (b w) c").shape
  155. torch.Size([30, 1280, 3])
  156. >>> # reordered axes to "b c h w" format for deep learning
  157. >>> rearrange(images, "b h w c -> b c h w").shape
  158. torch.Size([32, 3, 30, 40])
  159. >>> # flattened each image into a vector, 3600 = 30 * 40 * 3
  160. >>> rearrange(images, "b h w c -> b (c h w)").shape
  161. torch.Size([32, 3600])
  162. >>> # split each image into 4 smaller (top-left, top-right, bottom-left, bottom-right), 128 = 32 * 2 * 2
  163. >>> rearrange(images, "b (h1 h) (w1 w) c -> (b h1 w1) h w c", h1=2, w1=2).shape
  164. torch.Size([128, 15, 20, 3])
  165. >>> # space-to-depth operation
  166. >>> rearrange(images, "b (h h1) (w w1) c -> b h w (c h1 w1)", h1=2, w1=2).shape
  167. torch.Size([32, 15, 20, 12])
  168. """
  169. if not isinstance(tensor, torch.Tensor):
  170. tensor = torch.stack(tensor)
  171. rearrange_callable = _create_rearrange_callable(
  172. tensor.ndim, pattern, **axes_lengths
  173. )
  174. return rearrange_callable(tensor)