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

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