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.4 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2020 Megvii Inc. All rights reserved.
  5. #
  6. # Unless required by applicable law or agreed to in writing,
  7. # software distributed under the License is distributed on an
  8. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. from functools import partial
  10. import numpy as np
  11. import megengine.functional as F
  12. from megengine import tensor
  13. from megengine.test import assertTensorClose
  14. # from helpers import opr_test
  15. def _default_compare_fn(x, y):
  16. assertTensorClose(x.numpy(), y)
  17. def opr_test(cases, func, compare_fn=_default_compare_fn, ref_fn=None, **kwargs):
  18. """
  19. func: the function to run opr.
  20. compare_fn: the function to compare the result and expected, use assertTensorClose if None.
  21. ref_fn: the function to generate expected data, should assign output if None.
  22. cases: the list which have dict element, the list length should be 2 for dynamic shape test.
  23. and the dict should have input,
  24. and should have output if ref_fn is None.
  25. should use list for multiple inputs and outputs for each case.
  26. kwargs: The additional kwargs for opr func.
  27. simple examples:
  28. dtype = np.float32
  29. cases = [{"input": [10, 20]}, {"input": [20, 30]}]
  30. opr_test(cases,
  31. F.eye,
  32. ref_fn=lambda n, m: np.eye(n, m).astype(dtype),
  33. dtype=dtype)
  34. """
  35. def check_results(results, expected):
  36. if not isinstance(results, tuple):
  37. results = (results,)
  38. for r, e in zip(results, expected):
  39. compare_fn(r, e)
  40. def get_param(cases, idx):
  41. case = cases[idx]
  42. inp = case.get("input", None)
  43. outp = case.get("output", None)
  44. if inp is None:
  45. raise ValueError("the test case should have input")
  46. if not isinstance(inp, list):
  47. inp = (inp,)
  48. else:
  49. inp = tuple(inp)
  50. if ref_fn is not None and callable(ref_fn):
  51. outp = ref_fn(*inp)
  52. if outp is None:
  53. raise ValueError("the test case should have output or reference function")
  54. if not isinstance(outp, list):
  55. outp = (outp,)
  56. else:
  57. outp = tuple(outp)
  58. return inp, outp
  59. if len(cases) == 0:
  60. raise ValueError("should give one case at least")
  61. if not callable(func):
  62. raise ValueError("the input func should be callable")
  63. inp, outp = get_param(cases, 0)
  64. inp_tensor = [tensor(inpi) for inpi in inp]
  65. results = func(*inp_tensor, **kwargs)
  66. check_results(results, outp)
  67. def common_test_reduce(opr, ref_opr):
  68. data1_shape = (5, 6, 7)
  69. data2_shape = (2, 9, 12)
  70. data1 = np.random.random(data1_shape).astype(np.float32)
  71. data2 = np.random.random(data2_shape).astype(np.float32)
  72. cases = [{"input": data1}, {"input": data2}]
  73. if opr not in (F.argmin, F.argmax):
  74. # test default axis
  75. opr_test(cases, opr, ref_fn=ref_opr)
  76. # test all axises in range of input shape
  77. for axis in range(-3, 3):
  78. # test keepdims False
  79. opr_test(cases, opr, ref_fn=lambda x: ref_opr(x, axis=axis), axis=axis)
  80. # test keepdims True
  81. opr_test(
  82. cases,
  83. opr,
  84. ref_fn=lambda x: ref_opr(x, axis=axis, keepdims=True),
  85. axis=axis,
  86. keepdims=True,
  87. )
  88. else:
  89. # test defaut axis
  90. opr_test(cases, opr, ref_fn=lambda x: ref_opr(x).astype(np.int32))
  91. # test all axises in range of input shape
  92. for axis in range(0, 3):
  93. opr_test(
  94. cases,
  95. opr,
  96. ref_fn=lambda x: ref_opr(x, axis=axis).astype(np.int32),
  97. axis=axis,
  98. )
  99. def test_sum():
  100. common_test_reduce(opr=F.sum, ref_opr=np.sum)
  101. def test_prod():
  102. common_test_reduce(opr=F.prod, ref_opr=np.prod)
  103. def test_mean():
  104. common_test_reduce(opr=F.mean, ref_opr=np.mean)
  105. def test_var():
  106. common_test_reduce(opr=F.var, ref_opr=np.var)
  107. def test_std():
  108. common_test_reduce(opr=F.std, ref_opr=np.std)
  109. def test_min():
  110. common_test_reduce(opr=F.min, ref_opr=np.min)
  111. def test_max():
  112. common_test_reduce(opr=F.max, ref_opr=np.max)
  113. def test_argmin():
  114. common_test_reduce(opr=F.argmin, ref_opr=np.argmin)
  115. def test_argmax():
  116. common_test_reduce(opr=F.argmax, ref_opr=np.argmax)
  117. def test_sqrt():
  118. d1_shape = (15,)
  119. d2_shape = (25,)
  120. d1 = np.random.random(d1_shape).astype(np.float32)
  121. d2 = np.random.random(d2_shape).astype(np.float32)
  122. cases = [{"input": d1}, {"input": d2}]
  123. opr_test(cases, F.sqrt, ref_fn=np.sqrt)
  124. def test_sort():
  125. data1_shape = (10, 3)
  126. data2_shape = (12, 2)
  127. data1 = np.random.random(data1_shape).astype(np.float32)
  128. data2 = np.random.random(data2_shape).astype(np.float32)
  129. output0 = [np.sort(data1), np.argsort(data1).astype(np.int32)]
  130. output1 = [np.sort(data2), np.argsort(data2).astype(np.int32)]
  131. cases = [
  132. {"input": data1, "output": output0},
  133. {"input": data2, "output": output1},
  134. ]
  135. opr_test(cases, F.sort)
  136. def test_normalize():
  137. cases = [
  138. {"input": np.random.random((2, 3, 12, 12)).astype(np.float32)} for i in range(2)
  139. ]
  140. def np_normalize(x, p=2, axis=None, eps=1e-12):
  141. if axis is None:
  142. norm = np.sum(x ** p) ** (1.0 / p)
  143. else:
  144. norm = np.sum(x ** p, axis=axis, keepdims=True) ** (1.0 / p)
  145. return x / np.clip(norm, a_min=eps, a_max=np.inf)
  146. # Test L-2 norm along all dimensions
  147. opr_test(cases, F.normalize, ref_fn=np_normalize)
  148. # Test L-1 norm along all dimensions
  149. opr_test(cases, partial(F.normalize, p=1), ref_fn=partial(np_normalize, p=1))
  150. # Test L-2 norm along the second dimension
  151. opr_test(cases, partial(F.normalize, axis=1), ref_fn=partial(np_normalize, axis=1))
  152. # Test some norm == 0
  153. cases[0]["input"][0, 0, 0, :] = 0
  154. cases[1]["input"][0, 0, 0, :] = 0
  155. opr_test(cases, partial(F.normalize, axis=3), ref_fn=partial(np_normalize, axis=3))
  156. # def test_logsumexp():
  157. # x = np.arange(10).astype(np.float32)
  158. # expected = np.log(np.sum(np.exp(x)))
  159. # cases = [{"input": x, "output": expected}]
  160. # compare_fn = partial(assertTensorClose, allow_special_values=True)
  161. # # large value check
  162. # n = 100
  163. # x = np.full(n, 10000, dtype=np.float32)
  164. # expected = 10000 + np.log(n)
  165. # cases.append({"input": x, "output": expected.astype(np.float32)})
  166. # opr_test(cases, F.logsumexp, axis=0, compare_fn=compare_fn)
  167. # # special value check
  168. # x = np.array([np.inf], dtype=np.float32)
  169. # expected = x
  170. # cases = [{"input": x, "output": expected}]
  171. # x = np.array([-np.inf, 0.0], dtype=np.float32)
  172. # expected = np.zeros(1).astype(np.float32)
  173. # cases.append({"input": x, "output": expected})
  174. # opr_test(cases, F.logsumexp, axis=0, compare_fn=compare_fn)
  175. # x = np.array([np.nan], dtype=np.float32)
  176. # expected = x
  177. # cases = [{"input": x, "output": expected}]
  178. # x = np.array([-np.inf, 1], dtype=np.float32)
  179. # expected = np.array([1.0], dtype=np.float32)
  180. # cases.append({"input": x, "output": expected})
  181. # opr_test(cases, F.logsumexp, axis=0, compare_fn=compare_fn)
  182. # # keepdims check
  183. # x = np.array([[1e10, 1e-10], [-1e10, -np.inf]], dtype=np.float32)
  184. # expected = np.array([[1e10], [-1e10]], dtype=np.float32)
  185. # cases = [{"input": x, "output": expected}]
  186. # x = np.array([[1e10, -1e-10, 1e-10], [1e10, 1e-10, np.inf]], dtype=np.float32)
  187. # expected = np.array([[1e10], [np.inf]], dtype=np.float32)
  188. # cases.append({"input": x, "output": expected})
  189. # opr_test(cases, F.logsumexp, axis=1, keepdims=True, compare_fn=compare_fn)
  190. # # multiple axes check
  191. # x = np.array([[1e10, 1e-10], [-1e10, -np.inf]], dtype=np.float32)
  192. # expected = np.array([1e10], dtype=np.float32)
  193. # cases = [{"input": x, "output": expected}]
  194. # x = np.array([[1e10, -1e-10, 1e-10], [1e10, 1e-10, np.inf]], dtype=np.float32)
  195. # expected = np.array([np.inf], dtype=np.float32)
  196. # cases.append({"input": x, "output": expected})
  197. # opr_test(cases, F.logsumexp, axis=(0, 1), keepdims=False, compare_fn=compare_fn)

MegEngine 安装包中集成了使用 GPU 运行代码所需的 CUDA 环境,不用区分 CPU 和 GPU 版。 如果想要运行 GPU 程序,请确保机器本身配有 GPU 硬件设备并安装好驱动。 如果你想体验在云端 GPU 算力平台进行深度学习开发的感觉,欢迎访问 MegStudio 平台