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.

test_elemwise.py 5.6 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  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. import numpy as np
  10. import megengine.functional as F
  11. import megengine.functional.elemwise as elemwise
  12. from megengine import tensor
  13. from megengine.core.tensor import dtype
  14. from megengine.functional.elemwise import Elemwise, _elwise
  15. def test_abs():
  16. np.testing.assert_allclose(
  17. F.abs(tensor([-3.0, -4.0, -5.0])).numpy(),
  18. np.abs(np.array([-3.0, -4.0, -5.0], dtype=np.float32)),
  19. )
  20. np.testing.assert_allclose(F.abs(-3.0).numpy(), np.abs(np.float32(-3.0)))
  21. def test_elemwise_mode_string():
  22. for key, mode in vars(Elemwise.Mode).items():
  23. if isinstance(mode, Elemwise.Mode):
  24. assert key == mode
  25. assert Elemwise(mode=key) == Elemwise(mode=mode)
  26. def test_multiply():
  27. np.testing.assert_allclose(
  28. F.mul(-3.0, -4.0).numpy(), np.multiply(np.float32(-3.0), np.float32(-4.0))
  29. )
  30. np.testing.assert_allclose(
  31. F.mul(tensor([3.0, 4.0]), 4.0).numpy(),
  32. np.multiply(np.array([3.0, 4.0], dtype=np.float32), 4.0),
  33. )
  34. np.testing.assert_allclose(
  35. F.mul(4.0, tensor([3.0, 4.0])).numpy(),
  36. np.multiply(4.0, np.array([3.0, 4.0], dtype=np.float32)),
  37. )
  38. np.testing.assert_allclose(
  39. F.mul(tensor([3.0, 4.0]), tensor([3.0, 4.0])).numpy(),
  40. np.multiply(
  41. np.array([3.0, 4.0], dtype=np.float32),
  42. np.array([3.0, 4.0], dtype=np.float32),
  43. ),
  44. )
  45. def test_clamp():
  46. """Fix an issue when `lower` or `upper` is 0, it will be recognized as `False` and
  47. `F.clip` will fall into wrong conditions unexpectedly.
  48. """
  49. x = np.linspace(-6, 6, dtype="float32")
  50. np.testing.assert_allclose(
  51. F.clip(tensor(x) + 3, 0, 6).numpy(), np.clip(x + 3, 0, 6)
  52. )
  53. np.testing.assert_allclose(
  54. F.clip(tensor(x) - 3, -6, 0).numpy(), np.clip(x - 3, -6, 0)
  55. )
  56. def test_isnan():
  57. for case in [[1, float("nan"), 0]]:
  58. np.testing.assert_allclose(F.isnan(tensor(case)).numpy(), np.isnan(case))
  59. def test_isinf():
  60. for case in [[1, float("inf"), 0]]:
  61. np.testing.assert_allclose(F.isinf(tensor(case)).numpy(), np.isinf(case))
  62. def test_sign():
  63. for case in [[1, -1, 0]]:
  64. x = tensor(case)
  65. np.testing.assert_allclose(F.sign(x).numpy(), np.sign(case).astype(x.dtype))
  66. def test_cosh():
  67. np.random.seed(42)
  68. x = np.random.randn(100).astype("float32")
  69. y_np = np.cosh(x)
  70. y_mge = F.cosh(tensor(x)).numpy()
  71. np.testing.assert_allclose(y_np, y_mge, rtol=1e-5)
  72. def test_sinh():
  73. np.random.seed(42)
  74. x = np.random.randn(100).astype("float32")
  75. y_np = np.sinh(x)
  76. y_mge = F.sinh(tensor(x)).numpy()
  77. np.testing.assert_allclose(y_np, y_mge, rtol=1e-5)
  78. def test_asinh():
  79. np.random.seed(42)
  80. x = np.random.randn(100).astype("float32")
  81. y_np = np.arcsinh(x)
  82. y_mge = F.asinh(tensor(x)).numpy()
  83. np.testing.assert_almost_equal(y_np, y_mge, decimal=5)
  84. def test_acosh():
  85. x = np.arange(0, 10000).astype("float32") / 100 + 1
  86. y_np = np.arccosh(x)
  87. y_mge = F.acosh(tensor(x)).numpy()
  88. np.testing.assert_almost_equal(y_np, y_mge, decimal=6)
  89. def test_atanh():
  90. np.random.seed(42)
  91. x = np.random.rand(100).astype("float32") * 2 - 1
  92. y_np = np.arctanh(x)
  93. y_mge = F.atanh(tensor(x)).numpy()
  94. np.testing.assert_almost_equal(y_np, y_mge, decimal=5)
  95. def test_hswish():
  96. np.random.seed(42)
  97. x = np.random.randn(100).astype("float32")
  98. y_np = x * np.minimum(np.maximum(x + 3, 0), 6) / 6
  99. y_mge = F.hswish(tensor(x)).numpy()
  100. np.testing.assert_almost_equal(y_np, y_mge, decimal=6)
  101. def test_hsigmoid():
  102. np.random.seed(42)
  103. x = np.random.randn(100).astype("float32")
  104. y_np = np.minimum(np.maximum(x + 3, 0), 6) / 6
  105. y_mge = F.hsigmoid(tensor(x)).numpy()
  106. np.testing.assert_equal(y_np, y_mge)
  107. def test_logical_oprs():
  108. x = np.array([[True, False], [False, True]])
  109. y = np.array([[True, True], [False, False]])
  110. xx = tensor(x)
  111. yy = tensor(y)
  112. np.testing.assert_equal(~x, (F.logical_not(xx)).numpy())
  113. np.testing.assert_equal(x & y, F.logical_and(xx, yy).numpy())
  114. np.testing.assert_equal(x | y, F.logical_or(xx, yy).numpy())
  115. np.testing.assert_equal(x ^ y, F.logical_xor(xx, yy).numpy())
  116. def test_qadd():
  117. inp_scale = 0.5
  118. outp_scale = 0.2
  119. x = np.arange(6).reshape(2, 3).astype("float32")
  120. y = np.arange(6).reshape(2, 3).astype("float32")
  121. x = tensor(x, dtype=dtype.qint8(inp_scale))
  122. y = tensor(y, dtype=dtype.qint8(inp_scale))
  123. result_mge = F.elemwise._elemwise_multi_type(
  124. x, y, mode="qadd", dtype=dtype.qint8(outp_scale)
  125. )
  126. result_mge = result_mge.astype("float32").numpy()
  127. result_expect = x.astype("float32").numpy() + y.astype("float32").numpy()
  128. np.testing.assert_almost_equal(result_mge, result_expect, decimal=6)
  129. def test_int32_input():
  130. x = tensor(np.array([1, 2, 3, 4, 5]), dtype="int32")
  131. for op_name in elemwise.__all__:
  132. op = getattr(elemwise, op_name)
  133. nargs = op.__code__.co_argcount
  134. if op_name == "clip":
  135. inp = (x, 0, 1)
  136. elif op_name.endswith("_shift"):
  137. inp = (x, 1)
  138. elif op_name.startswith("logical_"):
  139. continue
  140. else:
  141. inp = (x,) * nargs
  142. y = op(*inp)
  143. y.numpy()

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