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.

utils.py 2.2 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import numpy as np
  2. from megengine import tensor
  3. def _default_compare_fn(x, y):
  4. np.testing.assert_allclose(x.numpy(), y, rtol=1e-6)
  5. def opr_test(cases, func, compare_fn=_default_compare_fn, ref_fn=None, **kwargs):
  6. """
  7. :param cases: the list which have dict element, the list length should be 2 for dynamic shape test.
  8. and the dict should have input,
  9. and should have output if ref_fn is None.
  10. should use list for multiple inputs and outputs for each case.
  11. :param func: the function to run opr.
  12. :param compare_fn: the function to compare the result and expected, use
  13. ``np.testing.assert_allclose`` if None.
  14. :param ref_fn: the function to generate expected data, should assign output if None.
  15. Examples:
  16. .. code-block::
  17. dtype = np.float32
  18. cases = [{"input": [10, 20]}, {"input": [20, 30]}]
  19. opr_test(cases,
  20. F.eye,
  21. ref_fn=lambda n, m: np.eye(n, m).astype(dtype),
  22. dtype=dtype)
  23. """
  24. def check_results(results, expected):
  25. if not isinstance(results, (tuple, list)):
  26. results = (results,)
  27. for r, e in zip(results, expected):
  28. compare_fn(r, e)
  29. def get_param(cases, idx):
  30. case = cases[idx]
  31. inp = case.get("input", None)
  32. outp = case.get("output", None)
  33. if inp is None:
  34. raise ValueError("the test case should have input")
  35. if not isinstance(inp, (tuple, list)):
  36. inp = (inp,)
  37. if ref_fn is not None and callable(ref_fn):
  38. outp = ref_fn(*inp)
  39. if outp is None:
  40. raise ValueError("the test case should have output or reference function")
  41. if not isinstance(outp, (tuple, list)):
  42. outp = (outp,)
  43. return inp, outp
  44. if len(cases) == 0:
  45. raise ValueError("should give one case at least")
  46. if not callable(func):
  47. raise ValueError("the input func should be callable")
  48. inp, outp = get_param(cases, 0)
  49. inp_tensor = [tensor(inpi) for inpi in inp]
  50. results = func(*inp_tensor, **kwargs)
  51. check_results(results, outp)

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