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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2021 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 ..core._imperative_rt.core2 import apply
  10. from ..core._imperative_rt.core2 import sync as _sync
  11. from ..core.ops.builtin import AssertEqual
  12. from ..tensor import Tensor
  13. from .elemwise import abs, maximum, minimum
  14. def _assert_equal(
  15. expect: Tensor, actual: Tensor, *, maxerr: float = 0.0001, verbose: bool = False
  16. ):
  17. r"""
  18. Asserts two tensors equal and returns expected value (first input).
  19. It is a variant of python assert which is symbolically traceable (similar to ``numpy.testing.assert_equal``).
  20. If we want to verify the correctness of model, just ``assert`` its states and outputs.
  21. While sometimes we need to verify the correctness at different backends for *dumped* model
  22. (or in :class:`~jit.trace` context), and no python code could be executed in that case.
  23. Thus we have to use :func:`~functional.utils._assert_equal` instead.
  24. :param expect: expected tensor value
  25. :param actual: tensor to check value
  26. :param maxerr: max allowed error; error is defined as the minimal of absolute and relative error
  27. :param verbose: whether to print maxerr to stdout during opr exec
  28. :return: expected tensor
  29. Examples:
  30. .. testcode::
  31. import numpy as np
  32. from megengine import tensor
  33. import megengine.functional as F
  34. x = tensor([1, 2, 3], np.float32)
  35. y = tensor([1, 2, 3], np.float32)
  36. print(F.utils._assert_equal(x, y, maxerr=0).numpy())
  37. Outputs:
  38. .. testoutput::
  39. [1. 2. 3.]
  40. """
  41. err = (
  42. abs(expect - actual)
  43. / maximum(minimum(abs(expect), abs(actual)), Tensor(1.0, dtype="float32"))
  44. ).max()
  45. result = apply(AssertEqual(maxerr=maxerr, verbose=verbose), expect, actual, err)[0]
  46. _sync() # sync interpreter to get exception
  47. return result

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