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.

__init__.py 2.5 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. import numpy as np
  10. def assertTensorClose(
  11. v0, v1, *, max_err: float = 1e-6, allow_special_values: bool = False, name=None
  12. ):
  13. """
  14. :param allow_special_values: whether to allow :attr:`v0` and :attr:`v1` to contain inf and nan values.
  15. :param max_err: relative error
  16. """
  17. __tracebackhide__ = True # pylint: disable=unused-variable
  18. assert (
  19. v0.dtype == v1.dtype
  20. ), "Two Tensor must have same dtype, but the inputs are {} and {}".format(
  21. v0.dtype, v1.dtype
  22. )
  23. v0 = np.ascontiguousarray(v0, dtype=np.float32).copy()
  24. v1 = np.ascontiguousarray(v1, dtype=np.float32).copy()
  25. if allow_special_values:
  26. # check nan and rm it
  27. v0_nan_mask = np.isnan(v0)
  28. if np.any(v0_nan_mask):
  29. assert np.array_equiv(v0_nan_mask, np.isnan(v1)), (v0, v1)
  30. v0[v0_nan_mask] = 0
  31. v1[v0_nan_mask] = 0
  32. # check inf and rm it
  33. v0_inf_mask = v0 == float("inf")
  34. if np.any(v0_inf_mask):
  35. assert np.array_equiv(v0_inf_mask, v1 == float("inf")), (v0, v1)
  36. v0[v0_inf_mask] = 0
  37. v1[v0_inf_mask] = 0
  38. # check -inf and rm it
  39. v0_inf_mask = v0 == float("-inf")
  40. if np.any(v0_inf_mask):
  41. assert np.array_equiv(v0_inf_mask, v1 == float("-inf")), (v0, v1)
  42. v0[v0_inf_mask] = 0
  43. v1[v0_inf_mask] = 0
  44. else:
  45. assert np.isfinite(v0.sum()) and np.isfinite(v1.sum()), (v0, v1)
  46. assert v0.shape == v1.shape, "Two tensor must have same shape({} v.s. {})".format(
  47. v0.shape, v1.shape
  48. )
  49. vdiv = np.max([np.abs(v0), np.abs(v1), np.ones_like(v0)], axis=0)
  50. err = np.abs(v0 - v1) / vdiv
  51. check = err > max_err
  52. if check.sum():
  53. idx = tuple(i[0] for i in np.nonzero(check))
  54. if name is None:
  55. name = "tensor"
  56. else:
  57. name = "tensor {}".format(name)
  58. raise AssertionError(
  59. "{} not equal: "
  60. "shape={} nonequal_idx={} v0={} v1={} err={}".format(
  61. name, v0.shape, idx, v0[idx], v1[idx], err[idx]
  62. )
  63. )

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