You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_elemwise.py 9.6 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. # -*- coding: utf-8 -*-
  2. import numpy as np
  3. import pytest
  4. import megengine.functional as F
  5. import megengine.functional.elemwise as elemwise
  6. from megengine import tensor
  7. from megengine.core.tensor import dtype
  8. from megengine.functional.elemwise import Elemwise
  9. from megengine.jit import trace
  10. def test_abs():
  11. np.testing.assert_allclose(
  12. F.abs(tensor([-3.0, -4.0, -5.0])).numpy(),
  13. np.abs(np.array([-3.0, -4.0, -5.0], dtype=np.float32)),
  14. )
  15. np.testing.assert_allclose(F.abs(-3.0).numpy(), np.abs(np.float32(-3.0)))
  16. def test_elemwise_mode_string():
  17. for key, mode in vars(Elemwise.Mode).items():
  18. if isinstance(mode, Elemwise.Mode):
  19. assert key == mode
  20. assert Elemwise(mode=key) == Elemwise(mode=mode)
  21. def test_multiply():
  22. np.testing.assert_allclose(
  23. F.mul(-3.0, -4.0).numpy(), np.multiply(np.float32(-3.0), np.float32(-4.0))
  24. )
  25. np.testing.assert_allclose(
  26. F.mul(tensor([3.0, 4.0]), 4.0).numpy(),
  27. np.multiply(np.array([3.0, 4.0], dtype=np.float32), 4.0),
  28. )
  29. np.testing.assert_allclose(
  30. F.mul(4.0, tensor([3.0, 4.0])).numpy(),
  31. np.multiply(4.0, np.array([3.0, 4.0], dtype=np.float32)),
  32. )
  33. np.testing.assert_allclose(
  34. F.mul(tensor([3.0, 4.0]), tensor([3.0, 4.0])).numpy(),
  35. np.multiply(
  36. np.array([3.0, 4.0], dtype=np.float32),
  37. np.array([3.0, 4.0], dtype=np.float32),
  38. ),
  39. )
  40. def test_div():
  41. np.testing.assert_allclose(
  42. F.div(tensor([3.0, 4.0]), 2).numpy(),
  43. np.divide(np.array([3, 4], dtype=np.float32), 2),
  44. )
  45. np.testing.assert_allclose(
  46. (tensor([3, 4]) / 2).numpy(), np.divide(np.array([3, 4], dtype=np.float32), 2),
  47. )
  48. np.testing.assert_allclose(
  49. F.floor_div(tensor([-5.0, -7.0]), 2).numpy(),
  50. np.floor_divide(np.array([-5.0, -7.0], dtype=np.float32), 2),
  51. )
  52. np.testing.assert_allclose(
  53. (tensor([-5, -7]) // 2).numpy(),
  54. np.floor_divide(np.array([-5, -7], dtype=np.int32), 2),
  55. )
  56. np.testing.assert_allclose(
  57. (tensor([[5, 4, 3], [4, 2, 6]]) // [1, 2, 1]).numpy(),
  58. np.floor_divide(np.array([[5, 4, 3], [4, 2, 6]], dtype=np.int32), [1, 2, 1]),
  59. )
  60. def test_clamp():
  61. """Fix an issue when `lower` or `upper` is 0, it will be recognized as `False` and
  62. `F.clip` will fall into wrong conditions unexpectedly.
  63. """
  64. x = np.linspace(-6, 6, dtype="float32")
  65. np.testing.assert_allclose(
  66. F.clip(tensor(x) + 3, 0, 6).numpy(), np.clip(x + 3, 0, 6)
  67. )
  68. np.testing.assert_allclose(
  69. F.clip(tensor(x) - 3, -6, 0).numpy(), np.clip(x - 3, -6, 0)
  70. )
  71. def test_isnan():
  72. for case in [[1, float("nan"), 0]]:
  73. np.testing.assert_allclose(F.isnan(tensor(case)).numpy(), np.isnan(case))
  74. def test_isinf():
  75. for case in [[1, float("inf"), 0]]:
  76. np.testing.assert_allclose(F.isinf(tensor(case)).numpy(), np.isinf(case))
  77. def test_sign():
  78. for case in [[1, -1, 0]]:
  79. x = tensor(case)
  80. np.testing.assert_allclose(F.sign(x).numpy(), np.sign(case).astype(x.dtype))
  81. def test_cosh():
  82. np.random.seed(42)
  83. x = np.random.randn(100).astype("float32")
  84. y_np = np.cosh(x)
  85. y_mge = F.cosh(tensor(x)).numpy()
  86. np.testing.assert_allclose(y_np, y_mge, rtol=1e-5)
  87. def test_sinh():
  88. np.random.seed(42)
  89. x = np.random.randn(100).astype("float32")
  90. y_np = np.sinh(x)
  91. y_mge = F.sinh(tensor(x)).numpy()
  92. np.testing.assert_allclose(y_np, y_mge, rtol=1e-5)
  93. def test_asinh():
  94. np.random.seed(42)
  95. x = np.random.randn(100).astype("float32")
  96. y_np = np.arcsinh(x)
  97. y_mge = F.asinh(tensor(x)).numpy()
  98. np.testing.assert_almost_equal(y_np, y_mge, decimal=5)
  99. def test_acosh():
  100. x = np.arange(0, 10000).astype("float32") / 100 + 1
  101. y_np = np.arccosh(x)
  102. y_mge = F.acosh(tensor(x)).numpy()
  103. np.testing.assert_almost_equal(y_np, y_mge, decimal=6)
  104. def test_atanh():
  105. np.random.seed(42)
  106. x = np.random.rand(100).astype("float32") * 2 - 1
  107. y_np = np.arctanh(x)
  108. y_mge = F.atanh(tensor(x)).numpy()
  109. np.testing.assert_almost_equal(y_np, y_mge, decimal=5)
  110. def test_hswish():
  111. np.random.seed(42)
  112. x = np.random.randn(100).astype("float32")
  113. y_np = x * np.minimum(np.maximum(x + 3, 0), 6) / 6
  114. y_mge = F.hswish(tensor(x)).numpy()
  115. np.testing.assert_almost_equal(y_np, y_mge, decimal=6)
  116. def test_silu():
  117. x = np.array([-1.5, 0.0, 1.0, 1.5]).astype("float32")
  118. y_np = x / (1 + np.exp(-x))
  119. y_mge = F.silu(tensor(x)).numpy()
  120. np.testing.assert_almost_equal(y_np, y_mge, decimal=6)
  121. def test_hsigmoid():
  122. np.random.seed(42)
  123. x = np.random.randn(100).astype("float32")
  124. y_np = np.minimum(np.maximum(x + 3, 0), 6) / 6
  125. y_mge = F.hsigmoid(tensor(x)).numpy()
  126. np.testing.assert_almost_equal(y_np, y_mge, decimal=6)
  127. def test_logical_oprs():
  128. x = np.array([[True, False], [False, True]])
  129. y = np.array([[True, True], [False, False]])
  130. xx = tensor(x)
  131. yy = tensor(y)
  132. np.testing.assert_equal(~x, (F.logical_not(xx)).numpy())
  133. np.testing.assert_equal(x & y, F.logical_and(xx, yy).numpy())
  134. np.testing.assert_equal(x | y, F.logical_or(xx, yy).numpy())
  135. np.testing.assert_equal(x ^ y, F.logical_xor(xx, yy).numpy())
  136. def test_logaddexp():
  137. x = np.random.randn(2, 100)
  138. y = np.random.randn(2, 100)
  139. xx = tensor(x)
  140. yy = tensor(y)
  141. out_np = np.log(np.exp(x) + np.exp(y))
  142. out_mge = F.logaddexp(xx, yy)
  143. np.testing.assert_almost_equal(out_np, out_mge.numpy(), decimal=6)
  144. def test_qadd():
  145. inp_scale = 0.5
  146. outp_scale = 0.2
  147. x = np.arange(6).reshape(2, 3).astype("float32")
  148. y = np.arange(6).reshape(2, 3).astype("float32")
  149. x = tensor(x, dtype=dtype.qint8(inp_scale))
  150. y = tensor(y, dtype=dtype.qint8(inp_scale))
  151. result_mge = F.elemwise._elemwise_multi_type(
  152. x, y, mode="qadd", dtype=dtype.qint8(outp_scale)
  153. )
  154. result_mge = result_mge.astype("float32").numpy()
  155. result_expect = x.astype("float32").numpy() + y.astype("float32").numpy()
  156. np.testing.assert_almost_equal(result_mge, result_expect, decimal=6)
  157. def test_int32_input():
  158. x = tensor(np.array([1, 2, 3, 4, 5]), dtype="int32")
  159. for op_name in elemwise.__all__:
  160. op = getattr(elemwise, op_name)
  161. nargs = op.__code__.co_argcount
  162. if op_name == "clip":
  163. inp = (x, 0, 1)
  164. elif op_name.endswith("_shift"):
  165. inp = (x, 1)
  166. elif op_name.startswith("logical_"):
  167. continue
  168. else:
  169. inp = (x,) * nargs
  170. y = op(*inp)
  171. y.numpy()
  172. @pytest.mark.parametrize("is_trace", [True, False])
  173. def test_empty_tensor(is_trace):
  174. binary_func = []
  175. unary_func = []
  176. for op_name in elemwise.__all__:
  177. op = getattr(elemwise, op_name)
  178. nargs = op.__code__.co_argcount
  179. if op_name == "clip":
  180. unary_func.append(["clip", lambda x, f=op: f(x, lower=0, upper=1)])
  181. elif op_name.endswith("_shift"):
  182. unary_func.append(
  183. [op_name, lambda x, f=op: f(tensor(x.numpy(), dtype="int32"), 1)]
  184. )
  185. elif op_name.startswith("logical_"): # logical_xxx op only accept boolean type
  186. if nargs == 1:
  187. unary_func.append(
  188. [op_name, lambda x, f=op: f(tensor(x.numpy(), dtype="bool"))]
  189. )
  190. else:
  191. assert nargs == 2
  192. binary_func.append(
  193. [
  194. op_name,
  195. lambda x, y, f=op: f(
  196. tensor(x.numpy(), dtype="bool"),
  197. tensor(y.numpy(), dtype="bool"),
  198. ),
  199. ]
  200. )
  201. elif nargs == 1:
  202. unary_func.append([op_name, op])
  203. elif nargs == 2:
  204. binary_func.append([op_name, op])
  205. else:
  206. raise NotImplementedError("nargs {}".format(nargs))
  207. def run_test(func, args, ref_shape, is_trace, sym=False):
  208. args = [tensor(t, dtype="float32") for t in args]
  209. if is_trace:
  210. func = trace(symbolic=sym)(func)
  211. for _ in range(3):
  212. out = func(*args)
  213. assert out.numpy().shape == ref_shape
  214. else:
  215. out = func(*args)
  216. assert out.numpy().shape == ref_shape, out.numpy().shape
  217. inps = [
  218. np.array([]).astype("float32"),
  219. np.random.randn(2, 0, 3).astype("float32"),
  220. 123,
  221. ]
  222. for op_name, op in unary_func:
  223. if is_trace:
  224. for sym in [True, False]:
  225. run_test(op, [inps[0],], inps[0].shape, True, sym)
  226. run_test(op, [inps[1],], inps[1].shape, True, sym)
  227. else:
  228. run_test(op, [inps[0],], inps[0].shape, False)
  229. run_test(op, [inps[1],], inps[1].shape, False)
  230. for op_name, op in binary_func:
  231. if is_trace:
  232. for sym in [True, False]:
  233. run_test(op, [inps[0], inps[0]], (inps[0] + inps[0]).shape, True, sym)
  234. run_test(op, [inps[1], inps[1]], (inps[1] + inps[1]).shape, True, sym)
  235. run_test(op, [inps[0], inps[2]], (inps[0] + inps[2]).shape, True, sym)
  236. run_test(op, [inps[1], inps[2]], (inps[1] + inps[2]).shape, True, sym)
  237. else:
  238. run_test(op, [inps[0], inps[0]], (inps[0] + inps[0]).shape, False)
  239. run_test(op, [inps[1], inps[1]], (inps[1] + inps[1]).shape, False)
  240. run_test(op, [inps[0], inps[2]], (inps[0] + inps[2]).shape, False)
  241. run_test(op, [inps[1], inps[2]], (inps[1] + inps[2]).shape, False)