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

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