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_math.py 8.0 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. # -*- coding: utf-8 -*-
  2. from functools import partial
  3. import numpy as np
  4. import pytest
  5. from utils import opr_test
  6. import megengine.functional as F
  7. from megengine import jit, tensor
  8. def common_test_reduce(opr, ref_opr):
  9. data1_shape = (5, 6, 7)
  10. data2_shape = (2, 9, 12)
  11. data1 = np.random.random(data1_shape).astype(np.float32)
  12. data2 = np.random.random(data2_shape).astype(np.float32)
  13. cases = [
  14. {"input": data1},
  15. {"input": data2},
  16. {"input": np.array([[[1, 2, np.nan, 4], [8, 6, 5, 2], [2, 3, 4, 5]]])},
  17. ]
  18. if opr not in (F.argmin, F.argmax):
  19. # test default axis
  20. opr_test(cases, opr, ref_fn=ref_opr)
  21. # test all axises in range of input shape
  22. for axis in range(-3, 3):
  23. # test keepdims False
  24. opr_test(cases, opr, ref_fn=lambda x: ref_opr(x, axis=axis), axis=axis)
  25. # test keepdims True
  26. opr_test(
  27. cases,
  28. opr,
  29. ref_fn=lambda x: ref_opr(x, axis=axis, keepdims=True),
  30. axis=axis,
  31. keepdims=True,
  32. )
  33. else:
  34. # test defaut axis
  35. opr_test(cases, opr, ref_fn=lambda x: ref_opr(x).astype(np.int32))
  36. # test all axises in range of input shape
  37. for axis in range(0, 3):
  38. opr_test(
  39. cases,
  40. opr,
  41. ref_fn=lambda x: ref_opr(x, axis=axis).astype(np.int32),
  42. axis=axis,
  43. )
  44. # test negative axis
  45. axis = axis - len(data1_shape)
  46. opr_test(
  47. cases,
  48. opr,
  49. ref_fn=lambda x: ref_opr(x, axis=axis).astype(np.int32),
  50. axis=axis,
  51. )
  52. def test_sum():
  53. common_test_reduce(opr=F.sum, ref_opr=np.sum)
  54. def test_prod():
  55. common_test_reduce(opr=F.prod, ref_opr=np.prod)
  56. def test_mean():
  57. common_test_reduce(opr=F.mean, ref_opr=np.mean)
  58. def test_var():
  59. common_test_reduce(opr=F.var, ref_opr=np.var)
  60. def test_std():
  61. common_test_reduce(opr=F.std, ref_opr=np.std)
  62. def test_min():
  63. common_test_reduce(opr=F.min, ref_opr=np.min)
  64. def test_max():
  65. common_test_reduce(opr=F.max, ref_opr=np.max)
  66. def test_argmin():
  67. common_test_reduce(opr=F.argmin, ref_opr=np.argmin)
  68. def test_argmax():
  69. common_test_reduce(opr=F.argmax, ref_opr=np.argmax)
  70. def test_sqrt():
  71. d1_shape = (15,)
  72. d2_shape = (25,)
  73. d1 = np.random.random(d1_shape).astype(np.float32)
  74. d2 = np.random.random(d2_shape).astype(np.float32)
  75. cases = [{"input": d1}, {"input": d2}]
  76. opr_test(cases, F.sqrt, ref_fn=np.sqrt)
  77. def test_sort():
  78. data1_shape = (10, 3)
  79. data2_shape = (12, 2)
  80. data1 = np.random.random(data1_shape).astype(np.float32)
  81. data2 = np.random.random(data2_shape).astype(np.float32)
  82. output1 = [np.sort(data1), np.argsort(data1).astype(np.int32)]
  83. output2 = [np.sort(data2), np.argsort(data2).astype(np.int32)]
  84. cases = [
  85. {"input": data1, "output": output1},
  86. {"input": data2, "output": output2},
  87. ]
  88. opr_test(cases, F.sort)
  89. @pytest.mark.parametrize("is_symbolic", [None, False, True])
  90. def test_sort_empty(is_symbolic):
  91. data_shapes = [
  92. (0,),
  93. (10, 0),
  94. ]
  95. def fn(x):
  96. return F.sort(x)
  97. for shape in data_shapes:
  98. if is_symbolic is not None:
  99. fn_ = jit.trace(symbolic=is_symbolic)(fn)
  100. else:
  101. fn_ = fn
  102. data = np.random.random(shape).astype(np.float32)
  103. for _ in range(3):
  104. outs = fn_(tensor(data))
  105. ref_outs = (np.sort(data), np.argsort(data))
  106. assert len(ref_outs) == len(outs)
  107. for i in range(len(outs)):
  108. np.testing.assert_equal(outs[i].numpy(), ref_outs[i])
  109. if is_symbolic is None:
  110. break
  111. def test_normalize():
  112. cases = [
  113. {"input": np.random.random((2, 3, 12, 12)).astype(np.float32)} for i in range(2)
  114. ]
  115. def np_normalize(x, p=2, axis=None, eps=1e-12):
  116. if axis is None:
  117. norm = np.sum(x ** p) ** (1.0 / p)
  118. else:
  119. norm = np.sum(x ** p, axis=axis, keepdims=True) ** (1.0 / p)
  120. return x / np.clip(norm, a_min=eps, a_max=np.inf)
  121. # # Test L-2 norm along all dimensions
  122. # opr_test(cases, F.normalize, ref_fn=np_normalize)
  123. # # Test L-1 norm along all dimensions
  124. # opr_test(cases, partial(F.normalize, p=1), ref_fn=partial(np_normalize, p=1))
  125. # Test L-2 norm along the second dimension
  126. opr_test(cases, partial(F.normalize, axis=1), ref_fn=partial(np_normalize, axis=1))
  127. # Test some norm == 0
  128. cases[0]["input"][0, 0, 0, :] = 0
  129. cases[1]["input"][0, 0, 0, :] = 0
  130. opr_test(cases, partial(F.normalize, axis=3), ref_fn=partial(np_normalize, axis=3))
  131. def test_sum_neg_axis():
  132. shape = (2, 3)
  133. data = np.random.random(shape).astype(np.float32)
  134. for axis in (-1, -2, (-2, 1), (-1, 0)):
  135. get = F.sum(tensor(data), axis=axis)
  136. ref = np.sum(data, axis=axis)
  137. np.testing.assert_allclose(get.numpy(), ref, rtol=1e-6)
  138. with pytest.raises(AssertionError):
  139. F.sum(tensor(data), axis=(-1, 1))
  140. def test_non_finite():
  141. shape = (32, 3, 32, 32)
  142. data = []
  143. for i in range(2):
  144. data.append(np.random.random(shape).astype(np.float32))
  145. tensorList = [tensor(x) for x in data]
  146. rst = F.math._check_non_finite(tensorList, 0.7)
  147. np.testing.assert_equal(rst.numpy(), [0])
  148. for i in range(len(tensorList)):
  149. np.testing.assert_allclose(tensorList[i].numpy() / 0.7, data[i], rtol=1e-6)
  150. data[1][0][0][0][0] = float("inf")
  151. rst = F.math._check_non_finite([tensor(x) for x in data], 0.7)
  152. np.testing.assert_equal(rst.numpy(), [1])
  153. data[1][0][0][0][0] = float("nan")
  154. rst = F.math._check_non_finite([tensor(x) for x in data], 0.7)
  155. np.testing.assert_equal(rst.numpy(), [1])
  156. @pytest.mark.parametrize("descending", [True, False])
  157. @pytest.mark.parametrize("sorted", [True, False])
  158. @pytest.mark.parametrize("inp1d", [True, False])
  159. @pytest.mark.parametrize("kth_only", [True, False])
  160. def test_topk(descending, sorted, inp1d, kth_only):
  161. k = 3
  162. if inp1d:
  163. data = np.random.permutation(7)
  164. else:
  165. data = np.random.permutation(5 * 7).reshape(5, 7)
  166. data = data.astype(np.int32)
  167. def np_sort(x):
  168. if descending:
  169. return np.sort(x)[..., ::-1]
  170. return np.sort(x)
  171. res = F.topk(
  172. tensor(data), k, descending=descending, no_sort=(not sorted), kth_only=kth_only
  173. )
  174. values, indices = res
  175. values = values.numpy()
  176. indices = indices.numpy()
  177. if kth_only:
  178. np.testing.assert_equal(
  179. values, np.take_along_axis(data, indices[..., None], -1).squeeze(-1)
  180. )
  181. np.testing.assert_equal(values, np_sort(data)[..., k - 1])
  182. else:
  183. np.testing.assert_equal(values, np.take_along_axis(data, indices, -1))
  184. if not sorted:
  185. values = np_sort(values)
  186. np.testing.assert_equal(values, np_sort(data)[..., :k])
  187. @pytest.mark.parametrize("is_trace", [True, False])
  188. def test_reduce_on_empty_tensor(is_trace):
  189. dtypes = [np.float32, np.int32, np.bool]
  190. inputs = [
  191. (np.random.random((0,)), None),
  192. (np.random.random((3, 0, 2)), 1),
  193. (np.random.random((10, 10, 0, 10)), 0),
  194. ]
  195. def run_test(fn, ref_fn, input, dtype, axis=None, symbolic=False):
  196. if is_trace:
  197. fn = jit.trace(symbolic=symbolic)(fn)
  198. for i in range(3):
  199. out = fn(tensor(input, dtype=dtype), axis=axis).numpy()
  200. out_ref = ref_fn(input.astype(dtype), axis=axis)
  201. np.testing.assert_equal(out, out_ref)
  202. for dtype in dtypes:
  203. for inp, axis in inputs:
  204. run_test(F.sum, np.sum, inp, dtype, axis, True)
  205. run_test(F.sum, np.sum, inp, dtype, axis, False)
  206. run_test(F.prod, np.prod, inp, dtype, axis, True)
  207. run_test(F.prod, np.prod, inp, dtype, axis, False)