test_ops.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  1. import itertools
  2. import numpy
  3. import numpy as np
  4. import pytest
  5. from einops import EinopsError
  6. from einops.einops import rearrange, reduce, repeat, _enumerate_directions
  7. from einops.tests import collect_test_backends, is_backend_tested, FLOAT_REDUCTIONS as REDUCTIONS
  8. imp_op_backends = collect_test_backends(symbolic=False, layers=False)
  9. sym_op_backends = collect_test_backends(symbolic=True, layers=False)
  10. identity_patterns = [
  11. "...->...",
  12. "a b c d e-> a b c d e",
  13. "a b c d e ...-> ... a b c d e",
  14. "a b c d e ...-> a ... b c d e",
  15. "... a b c d e -> ... a b c d e",
  16. "a ... e-> a ... e",
  17. "a ... -> a ... ",
  18. "a ... c d e -> a (...) c d e",
  19. ]
  20. equivalent_rearrange_patterns = [
  21. ("a b c d e -> (a b) c d e", "a b ... -> (a b) ... "),
  22. ("a b c d e -> a b (c d) e", "... c d e -> ... (c d) e"),
  23. ("a b c d e -> a b c d e", "... -> ... "),
  24. ("a b c d e -> (a b c d e)", "... -> (...)"),
  25. ("a b c d e -> b (c d e) a", "a b ... -> b (...) a"),
  26. ("a b c d e -> b (a c d) e", "a b ... e -> b (a ...) e"),
  27. ]
  28. equivalent_reduction_patterns = [
  29. ("a b c d e -> ", " ... -> "),
  30. ("a b c d e -> (e a)", "a ... e -> (e a)"),
  31. ("a b c d e -> d (a e)", " a b c d e ... -> d (a e) "),
  32. ("a b c d e -> (a b)", " ... c d e -> (...) "),
  33. ]
  34. def test_collapsed_ellipsis_errors_out():
  35. x = numpy.zeros([1, 1, 1, 1, 1])
  36. rearrange(x, "a b c d ... -> a b c ... d")
  37. with pytest.raises(EinopsError):
  38. rearrange(x, "a b c d (...) -> a b c ... d")
  39. rearrange(x, "... -> (...)")
  40. with pytest.raises(EinopsError):
  41. rearrange(x, "(...) -> (...)")
  42. def test_ellipsis_ops_numpy():
  43. x = numpy.arange(2 * 3 * 4 * 5 * 6).reshape([2, 3, 4, 5, 6])
  44. for pattern in identity_patterns:
  45. assert numpy.array_equal(x, rearrange(x, pattern)), pattern
  46. for pattern1, pattern2 in equivalent_rearrange_patterns:
  47. assert numpy.array_equal(rearrange(x, pattern1), rearrange(x, pattern2))
  48. for reduction in ["min", "max", "sum"]:
  49. for pattern1, pattern2 in equivalent_reduction_patterns:
  50. assert numpy.array_equal(reduce(x, pattern1, reduction=reduction), reduce(x, pattern2, reduction=reduction))
  51. # now just check coincidence with numpy
  52. all_rearrange_patterns = [*identity_patterns]
  53. for pattern_pairs in equivalent_rearrange_patterns:
  54. all_rearrange_patterns.extend(pattern_pairs)
  55. def check_op_against_numpy(backend, numpy_input, pattern, axes_lengths, reduction="rearrange", is_symbolic=False):
  56. """
  57. Helper to test result of operation (rearrange or transpose) against numpy
  58. if reduction == 'rearrange', rearrange op is tested, otherwise reduce
  59. """
  60. def operation(x):
  61. if reduction == "rearrange":
  62. return rearrange(x, pattern, **axes_lengths)
  63. else:
  64. return reduce(x, pattern, reduction, **axes_lengths)
  65. numpy_result = operation(numpy_input)
  66. check_equal = numpy.array_equal
  67. p_none_dimension = 0.5
  68. if is_symbolic:
  69. symbol_shape = [d if numpy.random.random() >= p_none_dimension else None for d in numpy_input.shape]
  70. symbol = backend.create_symbol(shape=symbol_shape)
  71. result_symbol = operation(symbol)
  72. backend_result = backend.eval_symbol(result_symbol, [(symbol, numpy_input)])
  73. else:
  74. backend_result = operation(backend.from_numpy(numpy_input))
  75. backend_result = backend.to_numpy(backend_result)
  76. check_equal(numpy_result, backend_result)
  77. def test_ellipsis_ops_imperative():
  78. """Checking various patterns against numpy"""
  79. x = numpy.arange(2 * 3 * 4 * 5 * 6).reshape([2, 3, 4, 5, 6])
  80. for is_symbolic in [True, False]:
  81. for backend in collect_test_backends(symbolic=is_symbolic, layers=False):
  82. for pattern in identity_patterns + list(itertools.chain(*equivalent_rearrange_patterns)):
  83. check_op_against_numpy(
  84. backend, x, pattern, axes_lengths={}, reduction="rearrange", is_symbolic=is_symbolic
  85. )
  86. for reduction in ["min", "max", "sum"]:
  87. for pattern in itertools.chain(*equivalent_reduction_patterns):
  88. check_op_against_numpy(
  89. backend, x, pattern, axes_lengths={}, reduction=reduction, is_symbolic=is_symbolic
  90. )
  91. def test_rearrange_array_api():
  92. import numpy as xp
  93. from einops import array_api as AA
  94. if xp.__version__ < "2.0.0":
  95. pytest.skip()
  96. x = numpy.arange(2 * 3 * 4 * 5 * 6).reshape([2, 3, 4, 5, 6])
  97. for pattern in identity_patterns + list(itertools.chain(*equivalent_rearrange_patterns)):
  98. expected = rearrange(x, pattern)
  99. result = AA.rearrange(xp.from_dlpack(x), pattern)
  100. assert numpy.array_equal(AA.asnumpy(result + 0), expected)
  101. def test_reduce_array_api():
  102. import numpy as xp
  103. from einops import array_api as AA
  104. if xp.__version__ < "2.0.0":
  105. pytest.skip()
  106. x = numpy.arange(2 * 3 * 4 * 5 * 6).reshape([2, 3, 4, 5, 6])
  107. for pattern in itertools.chain(*equivalent_reduction_patterns):
  108. for reduction in ["min", "max", "sum"]:
  109. expected = reduce(x, pattern, reduction=reduction)
  110. result = AA.reduce(xp.from_dlpack(x), pattern, reduction=reduction)
  111. assert numpy.array_equal(AA.asnumpy(np.asarray(result + 0)), expected)
  112. def test_rearrange_consistency_numpy():
  113. shape = [1, 2, 3, 5, 7, 11]
  114. x = numpy.arange(numpy.prod(shape)).reshape(shape)
  115. for pattern in [
  116. "a b c d e f -> a b c d e f",
  117. "b a c d e f -> a b d e f c",
  118. "a b c d e f -> f e d c b a",
  119. "a b c d e f -> (f e) d (c b a)",
  120. "a b c d e f -> (f e d c b a)",
  121. ]:
  122. result = rearrange(x, pattern)
  123. assert len(numpy.setdiff1d(x, result)) == 0
  124. assert result.dtype == x.dtype
  125. result = rearrange(x, "a b c d e f -> a (b) (c d e) f")
  126. assert numpy.array_equal(x.flatten(), result.flatten())
  127. result = rearrange(x, "a aa aa1 a1a1 aaaa a11 -> a aa aa1 a1a1 aaaa a11")
  128. assert numpy.array_equal(x, result)
  129. result1 = rearrange(x, "a b c d e f -> f e d c b a")
  130. result2 = rearrange(x, "f e d c b a -> a b c d e f")
  131. assert numpy.array_equal(result1, result2)
  132. result = rearrange(rearrange(x, "a b c d e f -> (f d) c (e b) a"), "(f d) c (e b) a -> a b c d e f", b=2, d=5)
  133. assert numpy.array_equal(x, result)
  134. sizes = dict(zip("abcdef", shape))
  135. temp = rearrange(x, "a b c d e f -> (f d) c (e b) a", **sizes)
  136. result = rearrange(temp, "(f d) c (e b) a -> a b c d e f", **sizes)
  137. assert numpy.array_equal(x, result)
  138. x2 = numpy.arange(2 * 3 * 4).reshape([2, 3, 4])
  139. result = rearrange(x2, "a b c -> b c a")
  140. assert x2[1, 2, 3] == result[2, 3, 1]
  141. assert x2[0, 1, 2] == result[1, 2, 0]
  142. def test_rearrange_permutations_numpy():
  143. # tests random permutation of axes against two independent numpy ways
  144. for n_axes in range(1, 10):
  145. input = numpy.arange(2**n_axes).reshape([2] * n_axes)
  146. permutation = numpy.random.permutation(n_axes)
  147. left_expression = " ".join("i" + str(axis) for axis in range(n_axes))
  148. right_expression = " ".join("i" + str(axis) for axis in permutation)
  149. expression = left_expression + " -> " + right_expression
  150. result = rearrange(input, expression)
  151. for pick in numpy.random.randint(0, 2, [10, n_axes]):
  152. assert input[tuple(pick)] == result[tuple(pick[permutation])]
  153. for n_axes in range(1, 10):
  154. input = numpy.arange(2**n_axes).reshape([2] * n_axes)
  155. permutation = numpy.random.permutation(n_axes)
  156. left_expression = " ".join("i" + str(axis) for axis in range(n_axes)[::-1])
  157. right_expression = " ".join("i" + str(axis) for axis in permutation[::-1])
  158. expression = left_expression + " -> " + right_expression
  159. result = rearrange(input, expression)
  160. assert result.shape == input.shape
  161. expected_result = numpy.zeros_like(input)
  162. for original_axis, result_axis in enumerate(permutation):
  163. expected_result |= ((input >> original_axis) & 1) << result_axis
  164. assert numpy.array_equal(result, expected_result)
  165. def test_reduction_imperatives():
  166. for backend in imp_op_backends:
  167. print("Reduction tests for ", backend.framework_name)
  168. for reduction in REDUCTIONS:
  169. # slight redundancy for simpler order - numpy version is evaluated multiple times
  170. input = numpy.arange(2 * 3 * 4 * 5 * 6, dtype="int64").reshape([2, 3, 4, 5, 6])
  171. if reduction in ["mean", "prod"]:
  172. input = input / input.astype("float64").mean()
  173. test_cases = [
  174. ["a b c d e -> ", {}, getattr(input, reduction)()],
  175. ["a ... -> ", {}, getattr(input, reduction)()],
  176. ["(a1 a2) ... (e1 e2) -> ", dict(a1=1, e2=2), getattr(input, reduction)()],
  177. [
  178. "a b c d e -> (e c) a",
  179. {},
  180. getattr(input, reduction)(axis=(1, 3)).transpose(2, 1, 0).reshape([-1, 2]),
  181. ],
  182. [
  183. "a ... c d e -> (e c) a",
  184. {},
  185. getattr(input, reduction)(axis=(1, 3)).transpose(2, 1, 0).reshape([-1, 2]),
  186. ],
  187. [
  188. "a b c d e ... -> (e c) a",
  189. {},
  190. getattr(input, reduction)(axis=(1, 3)).transpose(2, 1, 0).reshape([-1, 2]),
  191. ],
  192. ["a b c d e -> (e c a)", {}, getattr(input, reduction)(axis=(1, 3)).transpose(2, 1, 0).reshape([-1])],
  193. ["(a a2) ... -> (a2 a) ...", dict(a2=1), input],
  194. ]
  195. for pattern, axes_lengths, expected_result in test_cases:
  196. result = reduce(backend.from_numpy(input.copy()), pattern, reduction=reduction, **axes_lengths)
  197. result = backend.to_numpy(result)
  198. assert numpy.allclose(result, expected_result), f"Failed at {pattern}"
  199. def test_reduction_symbolic():
  200. for backend in sym_op_backends:
  201. print("Reduction tests for ", backend.framework_name)
  202. for reduction in REDUCTIONS:
  203. input = numpy.arange(2 * 3 * 4 * 5 * 6, dtype="int64").reshape([2, 3, 4, 5, 6])
  204. input = input / input.astype("float64").mean()
  205. # slight redundancy for simpler order - numpy version is evaluated multiple times
  206. test_cases = [
  207. ["a b c d e -> ", {}, getattr(input, reduction)()],
  208. ["a ... -> ", {}, getattr(input, reduction)()],
  209. ["(a a2) ... (e e2) -> ", dict(a2=1, e2=1), getattr(input, reduction)()],
  210. [
  211. "a b c d e -> (e c) a",
  212. {},
  213. getattr(input, reduction)(axis=(1, 3)).transpose(2, 1, 0).reshape([-1, 2]),
  214. ],
  215. [
  216. "a ... c d e -> (e c) a",
  217. {},
  218. getattr(input, reduction)(axis=(1, 3)).transpose(2, 1, 0).reshape([-1, 2]),
  219. ],
  220. [
  221. "a b c d e ... -> (e c) a",
  222. {},
  223. getattr(input, reduction)(axis=(1, 3)).transpose(2, 1, 0).reshape([-1, 2]),
  224. ],
  225. ["a b c d e -> (e c a)", {}, getattr(input, reduction)(axis=(1, 3)).transpose(2, 1, 0).reshape([-1])],
  226. ["(a a2) ... -> (a2 a) ...", dict(a2=1), input],
  227. ]
  228. for pattern, axes_lengths, expected_numpy_result in test_cases:
  229. shapes = [input.shape, [None for _ in input.shape]]
  230. for shape in shapes:
  231. sym = backend.create_symbol(shape)
  232. result_sym = reduce(sym, pattern, reduction=reduction, **axes_lengths)
  233. result = backend.eval_symbol(result_sym, [(sym, input)])
  234. assert numpy.allclose(result, expected_numpy_result)
  235. if True:
  236. shape = []
  237. _axes_lengths = {**axes_lengths}
  238. for axis, length in zip("abcde", input.shape):
  239. # filling as much as possible with Nones
  240. if axis in pattern:
  241. shape.append(None)
  242. _axes_lengths[axis] = length
  243. else:
  244. shape.append(length)
  245. sym = backend.create_symbol(shape)
  246. result_sym = reduce(sym, pattern, reduction=reduction, **_axes_lengths)
  247. result = backend.eval_symbol(result_sym, [(sym, input)])
  248. assert numpy.allclose(result, expected_numpy_result)
  249. def test_reduction_stress_imperatives():
  250. for backend in imp_op_backends:
  251. print("Stress-testing reduction for ", backend.framework_name)
  252. for reduction in REDUCTIONS + ("rearrange",):
  253. dtype = "int64"
  254. coincide = numpy.array_equal
  255. if reduction in ["mean", "prod"]:
  256. dtype = "float64"
  257. coincide = numpy.allclose
  258. max_dim = 11
  259. if "oneflow" in backend.framework_name:
  260. max_dim = 7
  261. if "paddle" in backend.framework_name:
  262. max_dim = 9
  263. for n_axes in range(max_dim):
  264. shape = numpy.random.randint(2, 4, size=n_axes)
  265. permutation = numpy.random.permutation(n_axes)
  266. skipped = 0 if reduction == "rearrange" else numpy.random.randint(n_axes + 1)
  267. left = " ".join("x" + str(i) for i in range(n_axes))
  268. right = " ".join("x" + str(i) for i in permutation[skipped:])
  269. pattern = left + "->" + right
  270. x = numpy.arange(1, 1 + numpy.prod(shape), dtype=dtype).reshape(shape)
  271. if reduction == "prod":
  272. x /= x.mean() # to avoid overflows
  273. result1 = reduce(x, pattern, reduction=reduction)
  274. result2 = x.transpose(permutation)
  275. if skipped > 0:
  276. result2 = getattr(result2, reduction)(axis=tuple(range(skipped)))
  277. assert coincide(result1, result2)
  278. check_op_against_numpy(backend, x, pattern, reduction=reduction, axes_lengths={}, is_symbolic=False)
  279. def test_reduction_with_callable_imperatives():
  280. x_numpy = numpy.arange(2 * 3 * 4 * 5 * 6).reshape([2, 3, 4, 5, 6]).astype("float32")
  281. x_numpy /= x_numpy.max()
  282. def logsumexp_torch(x, tuple_of_axes):
  283. return x.logsumexp(tuple_of_axes)
  284. def logsumexp_tf(x, tuple_of_axes):
  285. import tensorflow as tf
  286. return tf.reduce_logsumexp(x, tuple_of_axes)
  287. def logsumexp_keras(x, tuple_of_axes):
  288. import tensorflow.keras.backend as k
  289. return k.logsumexp(x, tuple_of_axes)
  290. def logsumexp_numpy(x, tuple_of_axes):
  291. # very naive logsumexp to compare to
  292. minused = x.max(tuple_of_axes)
  293. y = x - x.max(tuple_of_axes, keepdims=True)
  294. y = numpy.exp(y)
  295. y = numpy.sum(y, axis=tuple_of_axes)
  296. return numpy.log(y) + minused
  297. from einops._backends import TorchBackend, TensorflowBackend, TFKerasBackend, NumpyBackend
  298. backend2callback = {
  299. TorchBackend.framework_name: logsumexp_torch,
  300. TensorflowBackend.framework_name: logsumexp_tf,
  301. TFKerasBackend.framework_name: logsumexp_keras,
  302. NumpyBackend.framework_name: logsumexp_numpy,
  303. }
  304. for backend in imp_op_backends:
  305. if backend.framework_name not in backend2callback:
  306. continue
  307. backend_callback = backend2callback[backend.framework_name]
  308. x_backend = backend.from_numpy(x_numpy)
  309. for pattern1, pattern2 in equivalent_reduction_patterns:
  310. print("Test reduction with callable for ", backend.framework_name, pattern1, pattern2)
  311. output_numpy = reduce(x_numpy, pattern1, reduction=logsumexp_numpy)
  312. output_backend = reduce(x_backend, pattern1, reduction=backend_callback)
  313. assert numpy.allclose(
  314. output_numpy,
  315. backend.to_numpy(output_backend),
  316. )
  317. def test_enumerating_directions():
  318. for backend in imp_op_backends:
  319. print("testing directions for", backend.framework_name)
  320. for shape in [[], [1], [1, 1, 1], [2, 3, 5, 7]]:
  321. x = numpy.arange(numpy.prod(shape)).reshape(shape)
  322. axes1 = _enumerate_directions(x)
  323. axes2 = _enumerate_directions(backend.from_numpy(x))
  324. assert len(axes1) == len(axes2) == len(shape)
  325. for ax1, ax2 in zip(axes1, axes2):
  326. ax2 = backend.to_numpy(ax2)
  327. assert ax1.shape == ax2.shape
  328. assert numpy.allclose(ax1, ax2)
  329. def test_concatenations_and_stacking():
  330. for backend in imp_op_backends:
  331. print("testing shapes for ", backend.framework_name)
  332. for n_arrays in [1, 2, 5]:
  333. shapes = [[], [1], [1, 1], [2, 3, 5, 7], [1] * 6]
  334. for shape in shapes:
  335. arrays1 = [numpy.arange(i, i + numpy.prod(shape)).reshape(shape) for i in range(n_arrays)]
  336. arrays2 = [backend.from_numpy(array) for array in arrays1]
  337. result0 = numpy.asarray(arrays1)
  338. result1 = rearrange(arrays1, "...->...")
  339. result2 = rearrange(arrays2, "...->...")
  340. assert numpy.array_equal(result0, result1)
  341. assert numpy.array_equal(result1, backend.to_numpy(result2))
  342. result1 = rearrange(arrays1, "b ... -> ... b")
  343. result2 = rearrange(arrays2, "b ... -> ... b")
  344. assert numpy.array_equal(result1, backend.to_numpy(result2))
  345. def test_gradients_imperatives():
  346. # lazy - just checking reductions
  347. for reduction in REDUCTIONS:
  348. if reduction in ("any", "all"):
  349. continue # non-differentiable ops
  350. x = numpy.arange(1, 1 + 2 * 3 * 4).reshape([2, 3, 4]).astype("float32")
  351. results = {}
  352. for backend in imp_op_backends:
  353. y0 = backend.from_numpy(x)
  354. if not hasattr(y0, "grad"):
  355. continue
  356. y1 = reduce(y0, "a b c -> c a", reduction=reduction)
  357. y2 = reduce(y1, "c a -> a c", reduction=reduction)
  358. y3 = reduce(y2, "a (c1 c2) -> a", reduction=reduction, c1=2)
  359. y4 = reduce(y3, "... -> ", reduction=reduction)
  360. y4.backward()
  361. grad = backend.to_numpy(y0.grad)
  362. results[backend.framework_name] = grad
  363. print("comparing gradients for", results.keys())
  364. for name1, grad1 in results.items():
  365. for name2, grad2 in results.items():
  366. assert numpy.allclose(grad1, grad2), [name1, name2, "provided different gradients"]
  367. def test_tiling_imperatives():
  368. for backend in imp_op_backends:
  369. print("Tiling tests for ", backend.framework_name)
  370. input = numpy.arange(2 * 3 * 5, dtype="int64").reshape([2, 1, 3, 1, 5])
  371. test_cases = [
  372. (1, 1, 1, 1, 1),
  373. (1, 2, 1, 3, 1),
  374. (3, 1, 1, 4, 1),
  375. ]
  376. for repeats in test_cases:
  377. expected = numpy.tile(input, repeats)
  378. converted = backend.from_numpy(input)
  379. repeated = backend.tile(converted, repeats)
  380. result = backend.to_numpy(repeated)
  381. assert numpy.array_equal(result, expected)
  382. def test_tiling_symbolic():
  383. for backend in sym_op_backends:
  384. print("Tiling tests for ", backend.framework_name)
  385. input = numpy.arange(2 * 3 * 5, dtype="int64").reshape([2, 1, 3, 1, 5])
  386. test_cases = [
  387. (1, 1, 1, 1, 1),
  388. (1, 2, 1, 3, 1),
  389. (3, 1, 1, 4, 1),
  390. ]
  391. for repeats in test_cases:
  392. expected = numpy.tile(input, repeats)
  393. sym = backend.create_symbol(input.shape)
  394. result = backend.eval_symbol(backend.tile(sym, repeats), [[sym, input]])
  395. assert numpy.array_equal(result, expected)
  396. sym = backend.create_symbol([None] * len(input.shape))
  397. result = backend.eval_symbol(backend.tile(sym, repeats), [[sym, input]])
  398. assert numpy.array_equal(result, expected)
  399. repeat_test_cases = [
  400. # all assume that input has shape [2, 3, 5]
  401. ("a b c -> c a b", dict()),
  402. ("a b c -> (c copy a b)", dict(copy=2, a=2, b=3, c=5)),
  403. ("a b c -> (a copy) b c ", dict(copy=1)),
  404. ("a b c -> (c a) (copy1 b copy2)", dict(a=2, copy1=1, copy2=2)),
  405. ("a ... -> a ... copy", dict(copy=4)),
  406. ("... c -> ... (copy1 c copy2)", dict(copy1=1, copy2=2)),
  407. ("... -> ... ", dict()),
  408. (" ... -> copy1 ... copy2 ", dict(copy1=2, copy2=3)),
  409. ("a b c -> copy1 a copy2 b c () ", dict(copy1=2, copy2=1)),
  410. ]
  411. def check_reversion(x, repeat_pattern, **sizes):
  412. """Checks repeat pattern by running reduction"""
  413. left, right = repeat_pattern.split("->")
  414. reduce_pattern = right + "->" + left
  415. repeated = repeat(x, repeat_pattern, **sizes)
  416. reduced_min = reduce(repeated, reduce_pattern, reduction="min", **sizes)
  417. reduced_max = reduce(repeated, reduce_pattern, reduction="max", **sizes)
  418. assert numpy.array_equal(x, reduced_min)
  419. assert numpy.array_equal(x, reduced_max)
  420. def test_repeat_numpy():
  421. # check repeat vs reduce. Repeat works ok if reverse reduction with min and max work well
  422. x = numpy.arange(2 * 3 * 5).reshape([2, 3, 5])
  423. x1 = repeat(x, "a b c -> copy a b c ", copy=1)
  424. assert numpy.array_equal(x[None], x1)
  425. for pattern, axis_dimensions in repeat_test_cases:
  426. check_reversion(x, pattern, **axis_dimensions)
  427. def test_repeat_imperatives():
  428. x = numpy.arange(2 * 3 * 5).reshape([2, 3, 5])
  429. for backend in imp_op_backends:
  430. print("Repeat tests for ", backend.framework_name)
  431. for pattern, axis_dimensions in repeat_test_cases:
  432. expected = repeat(x, pattern, **axis_dimensions)
  433. converted = backend.from_numpy(x)
  434. repeated = repeat(converted, pattern, **axis_dimensions)
  435. result = backend.to_numpy(repeated)
  436. assert numpy.array_equal(result, expected)
  437. def test_repeat_symbolic():
  438. x = numpy.arange(2 * 3 * 5).reshape([2, 3, 5])
  439. for backend in sym_op_backends:
  440. print("Repeat tests for ", backend.framework_name)
  441. for pattern, axis_dimensions in repeat_test_cases:
  442. expected = repeat(x, pattern, **axis_dimensions)
  443. sym = backend.create_symbol(x.shape)
  444. result = backend.eval_symbol(repeat(sym, pattern, **axis_dimensions), [[sym, x]])
  445. assert numpy.array_equal(result, expected)
  446. def test_repeat_array_api():
  447. import numpy as xp
  448. from einops import array_api as AA
  449. if xp.__version__ < "2.0.0":
  450. pytest.skip()
  451. x = numpy.arange(2 * 3 * 5).reshape([2, 3, 5])
  452. for pattern, axis_dimensions in repeat_test_cases:
  453. expected = repeat(x, pattern, **axis_dimensions)
  454. result = AA.repeat(xp.from_dlpack(x), pattern, **axis_dimensions)
  455. assert numpy.array_equal(AA.asnumpy(result + 0), expected)
  456. test_cases_repeat_anonymous = [
  457. # all assume that input has shape [1, 2, 4, 6]
  458. ("a b c d -> c a d b", dict()),
  459. ("a b c d -> (c 2 d a b)", dict(a=1, c=4, d=6)),
  460. ("1 b c d -> (d copy 1) 3 b c ", dict(copy=3)),
  461. ("1 ... -> 3 ... ", dict()),
  462. ("() ... d -> 1 (copy1 d copy2) ... ", dict(copy1=2, copy2=3)),
  463. ("1 b c d -> (1 1) (1 b) 2 c 3 d (1 1)", dict()),
  464. ]
  465. def test_anonymous_axes():
  466. x = numpy.arange(1 * 2 * 4 * 6).reshape([1, 2, 4, 6])
  467. for pattern, axis_dimensions in test_cases_repeat_anonymous:
  468. check_reversion(x, pattern, **axis_dimensions)
  469. def test_list_inputs():
  470. x = numpy.arange(2 * 3 * 4 * 5 * 6).reshape([2, 3, 4, 5, 6])
  471. assert numpy.array_equal(
  472. rearrange(list(x), "... -> (...)"),
  473. rearrange(x, "... -> (...)"),
  474. )
  475. assert numpy.array_equal(
  476. reduce(list(x), "a ... e -> (...)", "min"),
  477. reduce(x, "a ... e -> (...)", "min"),
  478. )
  479. assert numpy.array_equal(
  480. repeat(list(x), "... -> b (...)", b=3),
  481. repeat(x, "... -> b (...)", b=3),
  482. )
  483. def test_torch_compile_with_dynamic_shape():
  484. if not is_backend_tested("torch"):
  485. pytest.skip()
  486. import torch
  487. # somewhat reasonable debug messages
  488. torch._dynamo.config.verbose = True
  489. def func1(x):
  490. # test contains ellipsis
  491. a, b, c, *other = x.shape
  492. x = rearrange(x, "(a a2) b c ... -> b (c a2) (a ...)", a2=2)
  493. # test contains passing expression as axis length
  494. x = reduce(x, "b ca2 A -> b A", "sum", ca2=c * 2)
  495. return x
  496. # seems can't test static and dynamic in the same test run.
  497. # func1_compiled_static = torch.compile(func1, dynamic=False, fullgraph=True, backend='aot_eager')
  498. func1_compiled_dynamic = torch.compile(func1, dynamic=True, fullgraph=True, backend="aot_eager")
  499. x = torch.randn(size=[4, 5, 6, 3])
  500. assert torch.equal(func1_compiled_dynamic(x), func1(x))
  501. # check with input of different dimensionality, and with all shape elements changed
  502. x = torch.randn(size=[6, 3, 4, 2, 3])
  503. assert torch.equal(func1_compiled_dynamic(x), func1(x))
  504. def bit_count(x):
  505. return sum((x >> i) & 1 for i in range(20))
  506. def test_reduction_imperatives_booleans():
  507. """Checks that any/all reduction works in all frameworks"""
  508. x_np = numpy.asarray([(bit_count(x) % 2) == 0 for x in range(2**6)]).reshape([2] * 6)
  509. for backend in imp_op_backends:
  510. print("Reduction any/all tests for ", backend.framework_name)
  511. for axis in range(6):
  512. expected_result_any = numpy.any(x_np, axis=axis, keepdims=True)
  513. expected_result_all = numpy.all(x_np, axis=axis, keepdims=True)
  514. assert not numpy.array_equal(expected_result_any, expected_result_all)
  515. axes = list("abcdef")
  516. axes_in = list(axes)
  517. axes_out = list(axes)
  518. axes_out[axis] = "1"
  519. pattern = (" ".join(axes_in)) + " -> " + (" ".join(axes_out))
  520. res_any = reduce(backend.from_numpy(x_np), pattern, reduction="any")
  521. res_all = reduce(backend.from_numpy(x_np), pattern, reduction="all")
  522. assert numpy.array_equal(expected_result_any, backend.to_numpy(res_any))
  523. assert numpy.array_equal(expected_result_all, backend.to_numpy(res_all))
  524. # expected result: any/all
  525. expected_result_any = numpy.any(x_np, axis=(0, 1), keepdims=True)
  526. expected_result_all = numpy.all(x_np, axis=(0, 1), keepdims=True)
  527. pattern = "a b ... -> 1 1 ..."
  528. res_any = reduce(backend.from_numpy(x_np), pattern, reduction="any")
  529. res_all = reduce(backend.from_numpy(x_np), pattern, reduction="all")
  530. assert numpy.array_equal(expected_result_any, backend.to_numpy(res_any))
  531. assert numpy.array_equal(expected_result_all, backend.to_numpy(res_all))