_parsing.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. """Adapted from https://github.com/arogozhnikov/einops/blob/36c7bb16e57d6e57f8f3050f9e07abdf3f00469f/einops/parsing.py.
  2. MIT License
  3. Copyright (c) 2018 Alex Rogozhnikov
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in all
  11. copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  18. SOFTWARE.
  19. """
  20. from __future__ import annotations
  21. import keyword
  22. import warnings
  23. from typing import Optional, TYPE_CHECKING, Union
  24. if TYPE_CHECKING:
  25. from collections.abc import Collection, Mapping
  26. _ellipsis: str = "\u2026" # NB, this is a single unicode symbol. String is used as it is not a list, but can be iterated
  27. class AnonymousAxis:
  28. """Used by `ParsedExpression` to represent an axis with a size (> 1), but no associated identifier.
  29. Note: Different instances of this class are not equal to each other, even if they have the same value.
  30. """
  31. def __init__(self, value: str) -> None:
  32. self.value = int(value)
  33. if self.value < 1:
  34. raise ValueError(
  35. f"Anonymous axis should have positive length, not {self.value}"
  36. )
  37. def __repr__(self) -> str:
  38. return f"{self.value}-axis"
  39. class ParsedExpression:
  40. """Structure containing information about one side of an `einops`-style pattern (e.g. 'b c (h w)')."""
  41. def __init__(
  42. self,
  43. expression: str,
  44. *,
  45. allow_underscore: bool = False,
  46. allow_duplicates: bool = False,
  47. ) -> None:
  48. """Parse the expression and store relevant metadata.
  49. Args:
  50. expression (str): the `einops`-pattern to parse
  51. allow_underscore (bool): whether to allow axis identifier names to begin with an underscore
  52. allow_duplicates (bool): whether to allow an identifier to appear more than once in the expression
  53. """
  54. self.has_ellipsis: bool = False
  55. self.has_ellipsis_parenthesized: Optional[bool] = None
  56. self.identifiers: set[Union[str, AnonymousAxis]] = set()
  57. # that's axes like 2, 3, 4 or 5. Axes with size 1 are exceptional and replaced with empty composition
  58. self.has_non_unitary_anonymous_axes: bool = False
  59. # composition keeps structure of composite axes, see how different corner cases are handled in tests
  60. self.composition: list[Union[list[Union[str, AnonymousAxis]], str]] = []
  61. if "." in expression:
  62. if "..." not in expression:
  63. raise ValueError(
  64. "Expression may contain dots only inside ellipsis (...)"
  65. )
  66. if str.count(expression, "...") != 1 or str.count(expression, ".") != 3:
  67. raise ValueError(
  68. "Expression may contain dots only inside ellipsis (...); only one ellipsis for tensor "
  69. )
  70. expression = expression.replace("...", _ellipsis)
  71. self.has_ellipsis = True
  72. bracket_group: Optional[list[Union[str, AnonymousAxis]]] = None
  73. def add_axis_name(x: str) -> None:
  74. if x in self.identifiers:
  75. if not (allow_underscore and x == "_") and not allow_duplicates:
  76. raise ValueError(
  77. f"Indexing expression contains duplicate dimension '{x}'"
  78. )
  79. if x == _ellipsis:
  80. self.identifiers.add(_ellipsis)
  81. if bracket_group is None:
  82. self.composition.append(_ellipsis)
  83. self.has_ellipsis_parenthesized = False
  84. else:
  85. bracket_group.append(_ellipsis)
  86. self.has_ellipsis_parenthesized = True
  87. else:
  88. is_number = str.isdecimal(x)
  89. if is_number and int(x) == 1:
  90. # handling the case of anonymous axis of length 1
  91. if bracket_group is None:
  92. self.composition.append([])
  93. else:
  94. pass # no need to think about 1s inside parenthesis
  95. return
  96. is_axis_name, reason = self.check_axis_name_return_reason(
  97. x, allow_underscore=allow_underscore
  98. )
  99. if not (is_number or is_axis_name):
  100. raise ValueError(f"Invalid axis identifier: {x}\n{reason}")
  101. axis_name: Union[str, AnonymousAxis] = (
  102. AnonymousAxis(x) if is_number else x
  103. )
  104. self.identifiers.add(axis_name)
  105. if is_number:
  106. self.has_non_unitary_anonymous_axes = True
  107. if bracket_group is None:
  108. self.composition.append([axis_name])
  109. else:
  110. bracket_group.append(axis_name)
  111. current_identifier = None
  112. for char in expression:
  113. if char in "() ":
  114. if current_identifier is not None:
  115. add_axis_name(current_identifier)
  116. current_identifier = None
  117. if char == "(":
  118. if bracket_group is not None:
  119. raise ValueError(
  120. "Axis composition is one-level (brackets inside brackets not allowed)"
  121. )
  122. bracket_group = []
  123. elif char == ")":
  124. if bracket_group is None:
  125. raise ValueError("Brackets are not balanced")
  126. self.composition.append(bracket_group)
  127. bracket_group = None
  128. elif str.isalnum(char) or char in ["_", _ellipsis]:
  129. if current_identifier is None:
  130. current_identifier = char
  131. else:
  132. current_identifier += char
  133. else:
  134. raise ValueError(f"Unknown character '{char}'")
  135. if bracket_group is not None:
  136. raise ValueError(f"Imbalanced parentheses in expression: '{expression}'")
  137. if current_identifier is not None:
  138. add_axis_name(current_identifier)
  139. @staticmethod
  140. def check_axis_name_return_reason(
  141. name: str, allow_underscore: bool = False
  142. ) -> tuple[bool, str]:
  143. """Check if the given axis name is valid, and a message explaining why if not.
  144. Valid axes names are python identifiers except keywords, and should not start or end with an underscore.
  145. Args:
  146. name (str): the axis name to check
  147. allow_underscore (bool): whether axis names are allowed to start with an underscore
  148. Returns:
  149. tuple[bool, str]: whether the axis name is valid, a message explaining why if not
  150. """
  151. if not str.isidentifier(name):
  152. return False, "not a valid python identifier"
  153. elif name[0] == "_" or name[-1] == "_":
  154. if name == "_" and allow_underscore:
  155. return True, ""
  156. return False, "axis name should should not start or end with underscore"
  157. else:
  158. if keyword.iskeyword(name):
  159. warnings.warn(
  160. f"It is discouraged to use axes names that are keywords: {name}",
  161. RuntimeWarning,
  162. )
  163. if name == "axis":
  164. warnings.warn(
  165. "It is discouraged to use 'axis' as an axis name and will raise an error in future",
  166. FutureWarning,
  167. )
  168. return True, ""
  169. @staticmethod
  170. def check_axis_name(name: str) -> bool:
  171. """Check if the name is a valid axis name.
  172. Args:
  173. name (str): the axis name to check
  174. Returns:
  175. bool: whether the axis name is valid
  176. """
  177. is_valid, _ = ParsedExpression.check_axis_name_return_reason(name)
  178. return is_valid
  179. def parse_pattern(
  180. pattern: str, axes_lengths: Mapping[str, int]
  181. ) -> tuple[ParsedExpression, ParsedExpression]:
  182. """Parse an `einops`-style pattern into a left-hand side and right-hand side `ParsedExpression` object.
  183. Args:
  184. pattern (str): the `einops`-style rearrangement pattern
  185. axes_lengths (Mapping[str, int]): any additional length specifications for dimensions
  186. Returns:
  187. tuple[ParsedExpression, ParsedExpression]: a tuple containing the left-hand side and right-hand side expressions
  188. """
  189. # adapted from einops.einops._prepare_transformation_recipe
  190. # https://github.com/arogozhnikov/einops/blob/230ac1526c1f42c9e1f7373912c7f8047496df11/einops/einops.py
  191. try:
  192. left_str, right_str = pattern.split("->")
  193. except ValueError:
  194. raise ValueError("Pattern must contain a single '->' separator") from None
  195. if _ellipsis in axes_lengths:
  196. raise ValueError(f"'{_ellipsis}' is not an allowed axis identifier")
  197. left = ParsedExpression(left_str)
  198. right = ParsedExpression(right_str)
  199. if not left.has_ellipsis and right.has_ellipsis:
  200. raise ValueError(
  201. f"Ellipsis found in right side, but not left side of a pattern {pattern}"
  202. )
  203. if left.has_ellipsis and left.has_ellipsis_parenthesized:
  204. raise ValueError(
  205. f"Ellipsis is parenthesis in the left side is not allowed: {pattern}"
  206. )
  207. return left, right
  208. def validate_rearrange_expressions(
  209. left: ParsedExpression, right: ParsedExpression, axes_lengths: Mapping[str, int]
  210. ) -> None:
  211. """Perform expression validations that are specific to the `rearrange` operation.
  212. Args:
  213. left (ParsedExpression): left-hand side expression
  214. right (ParsedExpression): right-hand side expression
  215. axes_lengths (Mapping[str, int]): any additional length specifications for dimensions
  216. """
  217. for length in axes_lengths.values():
  218. if (length_type := type(length)) is not int:
  219. raise TypeError(
  220. f"rearrange axis lengths must be integers, got: {length_type}"
  221. )
  222. if left.has_non_unitary_anonymous_axes or right.has_non_unitary_anonymous_axes:
  223. raise ValueError("rearrange only supports unnamed axes of size 1")
  224. difference = set.symmetric_difference(left.identifiers, right.identifiers)
  225. if len(difference) > 0:
  226. raise ValueError(
  227. f"Identifiers only on one side of rearrange expression (should be on both): {difference}"
  228. )
  229. unmatched_axes = axes_lengths.keys() - left.identifiers
  230. if len(unmatched_axes) > 0:
  231. raise ValueError(
  232. f"Identifiers not found in rearrange expression: {unmatched_axes}"
  233. )
  234. def comma_separate(collection: Collection[Union[str, Collection[str]]]) -> str:
  235. """Convert a collection of strings representing first class dims into a comma-separated string.
  236. Args:
  237. collection (Collection[Union[str, Collection[str]]]): the collection of strings to convert
  238. Returns:
  239. str: the comma-separated string
  240. Examples:
  241. >>> comma_separate(("d0",))
  242. 'd0'
  243. >>> comma_separate(("d0", "d1", "d2", "d3"))
  244. 'd0, d1, d2, d3'
  245. >>> comma_separate([("d1", "d4")])
  246. '(d1, d4)'
  247. >>> comma_separate([("d0",), (), ("d1",), ("d2",), ("d3", "d4")])
  248. '(d0,), (), (d1,), (d2,), (d3, d4)'
  249. """
  250. return ", ".join(
  251. item
  252. if isinstance(item, str)
  253. else f"({comma_separate(item)}{',' if len(item) == 1 else ''})"
  254. for item in collection
  255. )